applied-ai-018 commited on
Commit
3a52800
·
verified ·
1 Parent(s): 24091ef

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/__init__.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/delta.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_intlimits.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_limits.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/gosper.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/guess.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/products.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/summations.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_delta.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_guess.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_products.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/printing/__init__.py +116 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/printing/codeprinter.py +875 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/printing/cxx.py +169 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/printing/defaults.py +5 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/printing/fortran.py +782 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/printing/glsl.py +557 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/printing/gtk.py +16 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/printing/jscode.py +339 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/printing/julia.py +658 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/printing/lambdarepr.py +251 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/printing/latex.py +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py +489 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/printing/maple.py +311 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/printing/mathematica.py +354 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/printing/mathml.py +2126 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/printing/numpy.py +507 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/printing/octave.py +719 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/printing/preview.py +390 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/printing/printer.py +396 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/printing/pycode.py +750 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/printing/python.py +93 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/printing/repr.py +342 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/printing/str.py +1027 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__init__.py +0 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_aesaracode.py +626 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_c.py +875 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_codeprinter.py +55 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_conventions.py +116 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_cupy.py +55 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_cxx.py +67 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_dot.py +134 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_fortran.py +853 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_glsl.py +998 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_gtk.py +18 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_jax.py +347 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_jscode.py +396 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_julia.py +388 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_lambdarepr.py +246 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_latex.py +0 -0
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (336 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/delta.cpython-310.pyc ADDED
Binary file (9.22 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_intlimits.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_limits.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/gosper.cpython-310.pyc ADDED
Binary file (5.41 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/guess.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/products.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__pycache__/summations.cpython-310.pyc ADDED
Binary file (42.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_delta.cpython-310.pyc ADDED
Binary file (22.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_guess.cpython-310.pyc ADDED
Binary file (4.56 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_products.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/printing/__init__.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Printing subsystem"""
2
+
3
+ from .pretty import pager_print, pretty, pretty_print, pprint, pprint_use_unicode, pprint_try_use_unicode
4
+
5
+ from .latex import latex, print_latex, multiline_latex
6
+
7
+ from .mathml import mathml, print_mathml
8
+
9
+ from .python import python, print_python
10
+
11
+ from .pycode import pycode
12
+
13
+ from .codeprinter import print_ccode, print_fcode
14
+
15
+ from .codeprinter import ccode, fcode, cxxcode # noqa:F811
16
+
17
+ from .smtlib import smtlib_code
18
+
19
+ from .glsl import glsl_code, print_glsl
20
+
21
+ from .rcode import rcode, print_rcode
22
+
23
+ from .jscode import jscode, print_jscode
24
+
25
+ from .julia import julia_code
26
+
27
+ from .mathematica import mathematica_code
28
+
29
+ from .octave import octave_code
30
+
31
+ from .rust import rust_code
32
+
33
+ from .gtk import print_gtk
34
+
35
+ from .preview import preview
36
+
37
+ from .repr import srepr
38
+
39
+ from .tree import print_tree
40
+
41
+ from .str import StrPrinter, sstr, sstrrepr
42
+
43
+ from .tableform import TableForm
44
+
45
+ from .dot import dotprint
46
+
47
+ from .maple import maple_code, print_maple_code
48
+
49
+ __all__ = [
50
+ # sympy.printing.pretty
51
+ 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
52
+ 'pprint_try_use_unicode',
53
+
54
+ # sympy.printing.latex
55
+ 'latex', 'print_latex', 'multiline_latex',
56
+
57
+ # sympy.printing.mathml
58
+ 'mathml', 'print_mathml',
59
+
60
+ # sympy.printing.python
61
+ 'python', 'print_python',
62
+
63
+ # sympy.printing.pycode
64
+ 'pycode',
65
+
66
+ # sympy.printing.codeprinter
67
+ 'ccode', 'print_ccode', 'cxxcode', 'fcode', 'print_fcode',
68
+
69
+ # sympy.printing.smtlib
70
+ 'smtlib_code',
71
+
72
+ # sympy.printing.glsl
73
+ 'glsl_code', 'print_glsl',
74
+
75
+ # sympy.printing.rcode
76
+ 'rcode', 'print_rcode',
77
+
78
+ # sympy.printing.jscode
79
+ 'jscode', 'print_jscode',
80
+
81
+ # sympy.printing.julia
82
+ 'julia_code',
83
+
84
+ # sympy.printing.mathematica
85
+ 'mathematica_code',
86
+
87
+ # sympy.printing.octave
88
+ 'octave_code',
89
+
90
+ # sympy.printing.rust
91
+ 'rust_code',
92
+
93
+ # sympy.printing.gtk
94
+ 'print_gtk',
95
+
96
+ # sympy.printing.preview
97
+ 'preview',
98
+
99
+ # sympy.printing.repr
100
+ 'srepr',
101
+
102
+ # sympy.printing.tree
103
+ 'print_tree',
104
+
105
+ # sympy.printing.str
106
+ 'StrPrinter', 'sstr', 'sstrrepr',
107
+
108
+ # sympy.printing.tableform
109
+ 'TableForm',
110
+
111
+ # sympy.printing.dot
112
+ 'dotprint',
113
+
114
+ # sympy.printing.maple
115
+ 'maple_code', 'print_maple_code',
116
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/printing/codeprinter.py ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ from functools import wraps
5
+
6
+ from sympy.core import Add, Mul, Pow, S, sympify, Float
7
+ from sympy.core.basic import Basic
8
+ from sympy.core.expr import UnevaluatedExpr
9
+ from sympy.core.function import Lambda
10
+ from sympy.core.mul import _keep_coeff
11
+ from sympy.core.sorting import default_sort_key
12
+ from sympy.core.symbol import Symbol
13
+ from sympy.functions.elementary.complexes import re
14
+ from sympy.printing.str import StrPrinter
15
+ from sympy.printing.precedence import precedence, PRECEDENCE
16
+
17
+
18
+ class requires:
19
+ """ Decorator for registering requirements on print methods. """
20
+ def __init__(self, **kwargs):
21
+ self._req = kwargs
22
+
23
+ def __call__(self, method):
24
+ def _method_wrapper(self_, *args, **kwargs):
25
+ for k, v in self._req.items():
26
+ getattr(self_, k).update(v)
27
+ return method(self_, *args, **kwargs)
28
+ return wraps(method)(_method_wrapper)
29
+
30
+
31
+ class AssignmentError(Exception):
32
+ """
33
+ Raised if an assignment variable for a loop is missing.
34
+ """
35
+ pass
36
+
37
+
38
+ def _convert_python_lists(arg):
39
+ if isinstance(arg, list):
40
+ from sympy.codegen.abstract_nodes import List
41
+ return List(*(_convert_python_lists(e) for e in arg))
42
+ elif isinstance(arg, tuple):
43
+ return tuple(_convert_python_lists(e) for e in arg)
44
+ else:
45
+ return arg
46
+
47
+
48
+ class CodePrinter(StrPrinter):
49
+ """
50
+ The base class for code-printing subclasses.
51
+ """
52
+
53
+ _operators = {
54
+ 'and': '&&',
55
+ 'or': '||',
56
+ 'not': '!',
57
+ }
58
+
59
+ _default_settings: dict[str, Any] = {
60
+ 'order': None,
61
+ 'full_prec': 'auto',
62
+ 'error_on_reserved': False,
63
+ 'reserved_word_suffix': '_',
64
+ 'human': True,
65
+ 'inline': False,
66
+ 'allow_unknown_functions': False,
67
+ }
68
+
69
+ # Functions which are "simple" to rewrite to other functions that
70
+ # may be supported
71
+ # function_to_rewrite : (function_to_rewrite_to, iterable_with_other_functions_required)
72
+ _rewriteable_functions = {
73
+ 'cot': ('tan', []),
74
+ 'csc': ('sin', []),
75
+ 'sec': ('cos', []),
76
+ 'acot': ('atan', []),
77
+ 'acsc': ('asin', []),
78
+ 'asec': ('acos', []),
79
+ 'coth': ('exp', []),
80
+ 'csch': ('exp', []),
81
+ 'sech': ('exp', []),
82
+ 'acoth': ('log', []),
83
+ 'acsch': ('log', []),
84
+ 'asech': ('log', []),
85
+ 'catalan': ('gamma', []),
86
+ 'fibonacci': ('sqrt', []),
87
+ 'lucas': ('sqrt', []),
88
+ 'beta': ('gamma', []),
89
+ 'sinc': ('sin', ['Piecewise']),
90
+ 'Mod': ('floor', []),
91
+ 'factorial': ('gamma', []),
92
+ 'factorial2': ('gamma', ['Piecewise']),
93
+ 'subfactorial': ('uppergamma', []),
94
+ 'RisingFactorial': ('gamma', ['Piecewise']),
95
+ 'FallingFactorial': ('gamma', ['Piecewise']),
96
+ 'binomial': ('gamma', []),
97
+ 'frac': ('floor', []),
98
+ 'Max': ('Piecewise', []),
99
+ 'Min': ('Piecewise', []),
100
+ 'Heaviside': ('Piecewise', []),
101
+ 'erf2': ('erf', []),
102
+ 'erfc': ('erf', []),
103
+ 'Li': ('li', []),
104
+ 'Ei': ('li', []),
105
+ 'dirichlet_eta': ('zeta', []),
106
+ 'riemann_xi': ('zeta', ['gamma']),
107
+ }
108
+
109
+ def __init__(self, settings=None):
110
+
111
+ super().__init__(settings=settings)
112
+ if not hasattr(self, 'reserved_words'):
113
+ self.reserved_words = set()
114
+
115
+ def _handle_UnevaluatedExpr(self, expr):
116
+ return expr.replace(re, lambda arg: arg if isinstance(
117
+ arg, UnevaluatedExpr) and arg.args[0].is_real else re(arg))
118
+
119
+ def doprint(self, expr, assign_to=None):
120
+ """
121
+ Print the expression as code.
122
+
123
+ Parameters
124
+ ----------
125
+ expr : Expression
126
+ The expression to be printed.
127
+
128
+ assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional)
129
+ If provided, the printed code will set the expression to a variable or multiple variables
130
+ with the name or names given in ``assign_to``.
131
+ """
132
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
133
+ from sympy.codegen.ast import CodeBlock, Assignment
134
+
135
+ def _handle_assign_to(expr, assign_to):
136
+ if assign_to is None:
137
+ return sympify(expr)
138
+ if isinstance(assign_to, (list, tuple)):
139
+ if len(expr) != len(assign_to):
140
+ raise ValueError('Failed to assign an expression of length {} to {} variables'.format(len(expr), len(assign_to)))
141
+ return CodeBlock(*[_handle_assign_to(lhs, rhs) for lhs, rhs in zip(expr, assign_to)])
142
+ if isinstance(assign_to, str):
143
+ if expr.is_Matrix:
144
+ assign_to = MatrixSymbol(assign_to, *expr.shape)
145
+ else:
146
+ assign_to = Symbol(assign_to)
147
+ elif not isinstance(assign_to, Basic):
148
+ raise TypeError("{} cannot assign to object of type {}".format(
149
+ type(self).__name__, type(assign_to)))
150
+ return Assignment(assign_to, expr)
151
+
152
+ expr = _convert_python_lists(expr)
153
+ expr = _handle_assign_to(expr, assign_to)
154
+
155
+ # Remove re(...) nodes due to UnevaluatedExpr.is_real always is None:
156
+ expr = self._handle_UnevaluatedExpr(expr)
157
+
158
+ # keep a set of expressions that are not strictly translatable to Code
159
+ # and number constants that must be declared and initialized
160
+ self._not_supported = set()
161
+ self._number_symbols = set()
162
+
163
+ lines = self._print(expr).splitlines()
164
+
165
+ # format the output
166
+ if self._settings["human"]:
167
+ frontlines = []
168
+ if self._not_supported:
169
+ frontlines.append(self._get_comment(
170
+ "Not supported in {}:".format(self.language)))
171
+ for expr in sorted(self._not_supported, key=str):
172
+ frontlines.append(self._get_comment(type(expr).__name__))
173
+ for name, value in sorted(self._number_symbols, key=str):
174
+ frontlines.append(self._declare_number_const(name, value))
175
+ lines = frontlines + lines
176
+ lines = self._format_code(lines)
177
+ result = "\n".join(lines)
178
+ else:
179
+ lines = self._format_code(lines)
180
+ num_syms = {(k, self._print(v)) for k, v in self._number_symbols}
181
+ result = (num_syms, self._not_supported, "\n".join(lines))
182
+ self._not_supported = set()
183
+ self._number_symbols = set()
184
+ return result
185
+
186
+ def _doprint_loops(self, expr, assign_to=None):
187
+ # Here we print an expression that contains Indexed objects, they
188
+ # correspond to arrays in the generated code. The low-level implementation
189
+ # involves looping over array elements and possibly storing results in temporary
190
+ # variables or accumulate it in the assign_to object.
191
+
192
+ if self._settings.get('contract', True):
193
+ from sympy.tensor import get_contraction_structure
194
+ # Setup loops over non-dummy indices -- all terms need these
195
+ indices = self._get_expression_indices(expr, assign_to)
196
+ # Setup loops over dummy indices -- each term needs separate treatment
197
+ dummies = get_contraction_structure(expr)
198
+ else:
199
+ indices = []
200
+ dummies = {None: (expr,)}
201
+ openloop, closeloop = self._get_loop_opening_ending(indices)
202
+
203
+ # terms with no summations first
204
+ if None in dummies:
205
+ text = StrPrinter.doprint(self, Add(*dummies[None]))
206
+ else:
207
+ # If all terms have summations we must initialize array to Zero
208
+ text = StrPrinter.doprint(self, 0)
209
+
210
+ # skip redundant assignments (where lhs == rhs)
211
+ lhs_printed = self._print(assign_to)
212
+ lines = []
213
+ if text != lhs_printed:
214
+ lines.extend(openloop)
215
+ if assign_to is not None:
216
+ text = self._get_statement("%s = %s" % (lhs_printed, text))
217
+ lines.append(text)
218
+ lines.extend(closeloop)
219
+
220
+ # then terms with summations
221
+ for d in dummies:
222
+ if isinstance(d, tuple):
223
+ indices = self._sort_optimized(d, expr)
224
+ openloop_d, closeloop_d = self._get_loop_opening_ending(
225
+ indices)
226
+
227
+ for term in dummies[d]:
228
+ if term in dummies and not ([list(f.keys()) for f in dummies[term]]
229
+ == [[None] for f in dummies[term]]):
230
+ # If one factor in the term has it's own internal
231
+ # contractions, those must be computed first.
232
+ # (temporary variables?)
233
+ raise NotImplementedError(
234
+ "FIXME: no support for contractions in factor yet")
235
+ else:
236
+
237
+ # We need the lhs expression as an accumulator for
238
+ # the loops, i.e
239
+ #
240
+ # for (int d=0; d < dim; d++){
241
+ # lhs[] = lhs[] + term[][d]
242
+ # } ^.................. the accumulator
243
+ #
244
+ # We check if the expression already contains the
245
+ # lhs, and raise an exception if it does, as that
246
+ # syntax is currently undefined. FIXME: What would be
247
+ # a good interpretation?
248
+ if assign_to is None:
249
+ raise AssignmentError(
250
+ "need assignment variable for loops")
251
+ if term.has(assign_to):
252
+ raise ValueError("FIXME: lhs present in rhs,\
253
+ this is undefined in CodePrinter")
254
+
255
+ lines.extend(openloop)
256
+ lines.extend(openloop_d)
257
+ text = "%s = %s" % (lhs_printed, StrPrinter.doprint(
258
+ self, assign_to + term))
259
+ lines.append(self._get_statement(text))
260
+ lines.extend(closeloop_d)
261
+ lines.extend(closeloop)
262
+
263
+ return "\n".join(lines)
264
+
265
+ def _get_expression_indices(self, expr, assign_to):
266
+ from sympy.tensor import get_indices
267
+ rinds, junk = get_indices(expr)
268
+ linds, junk = get_indices(assign_to)
269
+
270
+ # support broadcast of scalar
271
+ if linds and not rinds:
272
+ rinds = linds
273
+ if rinds != linds:
274
+ raise ValueError("lhs indices must match non-dummy"
275
+ " rhs indices in %s" % expr)
276
+
277
+ return self._sort_optimized(rinds, assign_to)
278
+
279
+ def _sort_optimized(self, indices, expr):
280
+
281
+ from sympy.tensor.indexed import Indexed
282
+
283
+ if not indices:
284
+ return []
285
+
286
+ # determine optimized loop order by giving a score to each index
287
+ # the index with the highest score are put in the innermost loop.
288
+ score_table = {}
289
+ for i in indices:
290
+ score_table[i] = 0
291
+
292
+ arrays = expr.atoms(Indexed)
293
+ for arr in arrays:
294
+ for p, ind in enumerate(arr.indices):
295
+ try:
296
+ score_table[ind] += self._rate_index_position(p)
297
+ except KeyError:
298
+ pass
299
+
300
+ return sorted(indices, key=lambda x: score_table[x])
301
+
302
+ def _rate_index_position(self, p):
303
+ """function to calculate score based on position among indices
304
+
305
+ This method is used to sort loops in an optimized order, see
306
+ CodePrinter._sort_optimized()
307
+ """
308
+ raise NotImplementedError("This function must be implemented by "
309
+ "subclass of CodePrinter.")
310
+
311
+ def _get_statement(self, codestring):
312
+ """Formats a codestring with the proper line ending."""
313
+ raise NotImplementedError("This function must be implemented by "
314
+ "subclass of CodePrinter.")
315
+
316
+ def _get_comment(self, text):
317
+ """Formats a text string as a comment."""
318
+ raise NotImplementedError("This function must be implemented by "
319
+ "subclass of CodePrinter.")
320
+
321
+ def _declare_number_const(self, name, value):
322
+ """Declare a numeric constant at the top of a function"""
323
+ raise NotImplementedError("This function must be implemented by "
324
+ "subclass of CodePrinter.")
325
+
326
+ def _format_code(self, lines):
327
+ """Take in a list of lines of code, and format them accordingly.
328
+
329
+ This may include indenting, wrapping long lines, etc..."""
330
+ raise NotImplementedError("This function must be implemented by "
331
+ "subclass of CodePrinter.")
332
+
333
+ def _get_loop_opening_ending(self, indices):
334
+ """Returns a tuple (open_lines, close_lines) containing lists
335
+ of codelines"""
336
+ raise NotImplementedError("This function must be implemented by "
337
+ "subclass of CodePrinter.")
338
+
339
+ def _print_Dummy(self, expr):
340
+ if expr.name.startswith('Dummy_'):
341
+ return '_' + expr.name
342
+ else:
343
+ return '%s_%d' % (expr.name, expr.dummy_index)
344
+
345
+ def _print_CodeBlock(self, expr):
346
+ return '\n'.join([self._print(i) for i in expr.args])
347
+
348
+ def _print_String(self, string):
349
+ return str(string)
350
+
351
+ def _print_QuotedString(self, arg):
352
+ return '"%s"' % arg.text
353
+
354
+ def _print_Comment(self, string):
355
+ return self._get_comment(str(string))
356
+
357
+ def _print_Assignment(self, expr):
358
+ from sympy.codegen.ast import Assignment
359
+ from sympy.functions.elementary.piecewise import Piecewise
360
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
361
+ from sympy.tensor.indexed import IndexedBase
362
+ lhs = expr.lhs
363
+ rhs = expr.rhs
364
+ # We special case assignments that take multiple lines
365
+ if isinstance(expr.rhs, Piecewise):
366
+ # Here we modify Piecewise so each expression is now
367
+ # an Assignment, and then continue on the print.
368
+ expressions = []
369
+ conditions = []
370
+ for (e, c) in rhs.args:
371
+ expressions.append(Assignment(lhs, e))
372
+ conditions.append(c)
373
+ temp = Piecewise(*zip(expressions, conditions))
374
+ return self._print(temp)
375
+ elif isinstance(lhs, MatrixSymbol):
376
+ # Here we form an Assignment for each element in the array,
377
+ # printing each one.
378
+ lines = []
379
+ for (i, j) in self._traverse_matrix_indices(lhs):
380
+ temp = Assignment(lhs[i, j], rhs[i, j])
381
+ code0 = self._print(temp)
382
+ lines.append(code0)
383
+ return "\n".join(lines)
384
+ elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or
385
+ rhs.has(IndexedBase)):
386
+ # Here we check if there is looping to be done, and if so
387
+ # print the required loops.
388
+ return self._doprint_loops(rhs, lhs)
389
+ else:
390
+ lhs_code = self._print(lhs)
391
+ rhs_code = self._print(rhs)
392
+ return self._get_statement("%s = %s" % (lhs_code, rhs_code))
393
+
394
+ def _print_AugmentedAssignment(self, expr):
395
+ lhs_code = self._print(expr.lhs)
396
+ rhs_code = self._print(expr.rhs)
397
+ return self._get_statement("{} {} {}".format(
398
+ *(self._print(arg) for arg in [lhs_code, expr.op, rhs_code])))
399
+
400
+ def _print_FunctionCall(self, expr):
401
+ return '%s(%s)' % (
402
+ expr.name,
403
+ ', '.join((self._print(arg) for arg in expr.function_args)))
404
+
405
+ def _print_Variable(self, expr):
406
+ return self._print(expr.symbol)
407
+
408
+ def _print_Symbol(self, expr):
409
+
410
+ name = super()._print_Symbol(expr)
411
+
412
+ if name in self.reserved_words:
413
+ if self._settings['error_on_reserved']:
414
+ msg = ('This expression includes the symbol "{}" which is a '
415
+ 'reserved keyword in this language.')
416
+ raise ValueError(msg.format(name))
417
+ return name + self._settings['reserved_word_suffix']
418
+ else:
419
+ return name
420
+
421
+ def _can_print(self, name):
422
+ """ Check if function ``name`` is either a known function or has its own
423
+ printing method. Used to check if rewriting is possible."""
424
+ return name in self.known_functions or getattr(self, '_print_{}'.format(name), False)
425
+
426
+ def _print_Function(self, expr):
427
+ if expr.func.__name__ in self.known_functions:
428
+ cond_func = self.known_functions[expr.func.__name__]
429
+ if isinstance(cond_func, str):
430
+ return "%s(%s)" % (cond_func, self.stringify(expr.args, ", "))
431
+ else:
432
+ for cond, func in cond_func:
433
+ if cond(*expr.args):
434
+ break
435
+ if func is not None:
436
+ try:
437
+ return func(*[self.parenthesize(item, 0) for item in expr.args])
438
+ except TypeError:
439
+ return "%s(%s)" % (func, self.stringify(expr.args, ", "))
440
+ elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):
441
+ # inlined function
442
+ return self._print(expr._imp_(*expr.args))
443
+ elif expr.func.__name__ in self._rewriteable_functions:
444
+ # Simple rewrite to supported function possible
445
+ target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
446
+ if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
447
+ return self._print(expr.rewrite(target_f))
448
+ if expr.is_Function and self._settings.get('allow_unknown_functions', False):
449
+ return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args)))
450
+ else:
451
+ return self._print_not_supported(expr)
452
+
453
+ _print_Expr = _print_Function
454
+
455
+ # Don't inherit the str-printer method for Heaviside to the code printers
456
+ _print_Heaviside = None
457
+
458
+ def _print_NumberSymbol(self, expr):
459
+ if self._settings.get("inline", False):
460
+ return self._print(Float(expr.evalf(self._settings["precision"])))
461
+ else:
462
+ # A Number symbol that is not implemented here or with _printmethod
463
+ # is registered and evaluated
464
+ self._number_symbols.add((expr,
465
+ Float(expr.evalf(self._settings["precision"]))))
466
+ return str(expr)
467
+
468
+ def _print_Catalan(self, expr):
469
+ return self._print_NumberSymbol(expr)
470
+ def _print_EulerGamma(self, expr):
471
+ return self._print_NumberSymbol(expr)
472
+ def _print_GoldenRatio(self, expr):
473
+ return self._print_NumberSymbol(expr)
474
+ def _print_TribonacciConstant(self, expr):
475
+ return self._print_NumberSymbol(expr)
476
+ def _print_Exp1(self, expr):
477
+ return self._print_NumberSymbol(expr)
478
+ def _print_Pi(self, expr):
479
+ return self._print_NumberSymbol(expr)
480
+
481
+ def _print_And(self, expr):
482
+ PREC = precedence(expr)
483
+ return (" %s " % self._operators['and']).join(self.parenthesize(a, PREC)
484
+ for a in sorted(expr.args, key=default_sort_key))
485
+
486
+ def _print_Or(self, expr):
487
+ PREC = precedence(expr)
488
+ return (" %s " % self._operators['or']).join(self.parenthesize(a, PREC)
489
+ for a in sorted(expr.args, key=default_sort_key))
490
+
491
+ def _print_Xor(self, expr):
492
+ if self._operators.get('xor') is None:
493
+ return self._print(expr.to_nnf())
494
+ PREC = precedence(expr)
495
+ return (" %s " % self._operators['xor']).join(self.parenthesize(a, PREC)
496
+ for a in expr.args)
497
+
498
+ def _print_Equivalent(self, expr):
499
+ if self._operators.get('equivalent') is None:
500
+ return self._print(expr.to_nnf())
501
+ PREC = precedence(expr)
502
+ return (" %s " % self._operators['equivalent']).join(self.parenthesize(a, PREC)
503
+ for a in expr.args)
504
+
505
+ def _print_Not(self, expr):
506
+ PREC = precedence(expr)
507
+ return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
508
+
509
+ def _print_BooleanFunction(self, expr):
510
+ return self._print(expr.to_nnf())
511
+
512
+ def _print_Mul(self, expr):
513
+
514
+ prec = precedence(expr)
515
+
516
+ c, e = expr.as_coeff_Mul()
517
+ if c < 0:
518
+ expr = _keep_coeff(-c, e)
519
+ sign = "-"
520
+ else:
521
+ sign = ""
522
+
523
+ a = [] # items in the numerator
524
+ b = [] # items that are in the denominator (if any)
525
+
526
+ pow_paren = [] # Will collect all pow with more than one base element and exp = -1
527
+
528
+ if self.order not in ('old', 'none'):
529
+ args = expr.as_ordered_factors()
530
+ else:
531
+ # use make_args in case expr was something like -x -> x
532
+ args = Mul.make_args(expr)
533
+
534
+ # Gather args for numerator/denominator
535
+ for item in args:
536
+ if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
537
+ if item.exp != -1:
538
+ b.append(Pow(item.base, -item.exp, evaluate=False))
539
+ else:
540
+ if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
541
+ pow_paren.append(item)
542
+ b.append(Pow(item.base, -item.exp))
543
+ else:
544
+ a.append(item)
545
+
546
+ a = a or [S.One]
547
+
548
+ if len(a) == 1 and sign == "-":
549
+ # Unary minus does not have a SymPy class, and hence there's no
550
+ # precedence weight associated with it, Python's unary minus has
551
+ # an operator precedence between multiplication and exponentiation,
552
+ # so we use this to compute a weight.
553
+ a_str = [self.parenthesize(a[0], 0.5*(PRECEDENCE["Pow"]+PRECEDENCE["Mul"]))]
554
+ else:
555
+ a_str = [self.parenthesize(x, prec) for x in a]
556
+ b_str = [self.parenthesize(x, prec) for x in b]
557
+
558
+ # To parenthesize Pow with exp = -1 and having more than one Symbol
559
+ for item in pow_paren:
560
+ if item.base in b:
561
+ b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
562
+
563
+ if not b:
564
+ return sign + '*'.join(a_str)
565
+ elif len(b) == 1:
566
+ return sign + '*'.join(a_str) + "/" + b_str[0]
567
+ else:
568
+ return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
569
+
570
+ def _print_not_supported(self, expr):
571
+ try:
572
+ self._not_supported.add(expr)
573
+ except TypeError:
574
+ # not hashable
575
+ pass
576
+ return self.emptyPrinter(expr)
577
+
578
+ # The following can not be simply translated into C or Fortran
579
+ _print_Basic = _print_not_supported
580
+ _print_ComplexInfinity = _print_not_supported
581
+ _print_Derivative = _print_not_supported
582
+ _print_ExprCondPair = _print_not_supported
583
+ _print_GeometryEntity = _print_not_supported
584
+ _print_Infinity = _print_not_supported
585
+ _print_Integral = _print_not_supported
586
+ _print_Interval = _print_not_supported
587
+ _print_AccumulationBounds = _print_not_supported
588
+ _print_Limit = _print_not_supported
589
+ _print_MatrixBase = _print_not_supported
590
+ _print_DeferredVector = _print_not_supported
591
+ _print_NaN = _print_not_supported
592
+ _print_NegativeInfinity = _print_not_supported
593
+ _print_Order = _print_not_supported
594
+ _print_RootOf = _print_not_supported
595
+ _print_RootsOf = _print_not_supported
596
+ _print_RootSum = _print_not_supported
597
+ _print_Uniform = _print_not_supported
598
+ _print_Unit = _print_not_supported
599
+ _print_Wild = _print_not_supported
600
+ _print_WildFunction = _print_not_supported
601
+ _print_Relational = _print_not_supported
602
+
603
+
604
+ # Code printer functions. These are included in this file so that they can be
605
+ # imported in the top-level __init__.py without importing the sympy.codegen
606
+ # module.
607
+
608
+ def ccode(expr, assign_to=None, standard='c99', **settings):
609
+ """Converts an expr to a string of c code
610
+
611
+ Parameters
612
+ ==========
613
+
614
+ expr : Expr
615
+ A SymPy expression to be converted.
616
+ assign_to : optional
617
+ When given, the argument is used as the name of the variable to which
618
+ the expression is assigned. Can be a string, ``Symbol``,
619
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
620
+ line-wrapping, or for expressions that generate multi-line statements.
621
+ standard : str, optional
622
+ String specifying the standard. If your compiler supports a more modern
623
+ standard you may set this to 'c99' to allow the printer to use more math
624
+ functions. [default='c89'].
625
+ precision : integer, optional
626
+ The precision for numbers such as pi [default=17].
627
+ user_functions : dict, optional
628
+ A dictionary where the keys are string representations of either
629
+ ``FunctionClass`` or ``UndefinedFunction`` instances and the values
630
+ are their desired C string representations. Alternatively, the
631
+ dictionary value can be a list of tuples i.e. [(argument_test,
632
+ cfunction_string)] or [(argument_test, cfunction_formater)]. See below
633
+ for examples.
634
+ dereference : iterable, optional
635
+ An iterable of symbols that should be dereferenced in the printed code
636
+ expression. These would be values passed by address to the function.
637
+ For example, if ``dereference=[a]``, the resulting code would print
638
+ ``(*a)`` instead of ``a``.
639
+ human : bool, optional
640
+ If True, the result is a single string that may contain some constant
641
+ declarations for the number symbols. If False, the same information is
642
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
643
+ code_text). [default=True].
644
+ contract: bool, optional
645
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
646
+ rules and the corresponding nested loops over indices are generated.
647
+ Setting contract=False will not generate loops, instead the user is
648
+ responsible to provide values for the indices in the code.
649
+ [default=True].
650
+
651
+ Examples
652
+ ========
653
+
654
+ >>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function
655
+ >>> x, tau = symbols("x, tau")
656
+ >>> expr = (2*tau)**Rational(7, 2)
657
+ >>> ccode(expr)
658
+ '8*M_SQRT2*pow(tau, 7.0/2.0)'
659
+ >>> ccode(expr, math_macros={})
660
+ '8*sqrt(2)*pow(tau, 7.0/2.0)'
661
+ >>> ccode(sin(x), assign_to="s")
662
+ 's = sin(x);'
663
+ >>> from sympy.codegen.ast import real, float80
664
+ >>> ccode(expr, type_aliases={real: float80})
665
+ '8*M_SQRT2l*powl(tau, 7.0L/2.0L)'
666
+
667
+ Simple custom printing can be defined for certain types by passing a
668
+ dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
669
+ Alternatively, the dictionary value can be a list of tuples i.e.
670
+ [(argument_test, cfunction_string)].
671
+
672
+ >>> custom_functions = {
673
+ ... "ceiling": "CEIL",
674
+ ... "Abs": [(lambda x: not x.is_integer, "fabs"),
675
+ ... (lambda x: x.is_integer, "ABS")],
676
+ ... "func": "f"
677
+ ... }
678
+ >>> func = Function('func')
679
+ >>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions)
680
+ 'f(fabs(x) + CEIL(x))'
681
+
682
+ or if the C-function takes a subset of the original arguments:
683
+
684
+ >>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [
685
+ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
686
+ ... (lambda b, e: b != 2, 'pow')]})
687
+ 'exp2(x) + pow(3, x)'
688
+
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
+
696
+ >>> from sympy import Piecewise
697
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
698
+ >>> print(ccode(expr, tau, standard='C89'))
699
+ if (x > 0) {
700
+ tau = x + 1;
701
+ }
702
+ else {
703
+ tau = x;
704
+ }
705
+
706
+ Support for loops is provided through ``Indexed`` types. With
707
+ ``contract=True`` these expressions will be turned into loops, whereas
708
+ ``contract=False`` will just print the assignment expression that should be
709
+ looped over:
710
+
711
+ >>> from sympy import Eq, IndexedBase, Idx
712
+ >>> len_y = 5
713
+ >>> y = IndexedBase('y', shape=(len_y,))
714
+ >>> t = IndexedBase('t', shape=(len_y,))
715
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
716
+ >>> i = Idx('i', len_y-1)
717
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
718
+ >>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89')
719
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
720
+
721
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
722
+ must be provided to ``assign_to``. Note that any expression that can be
723
+ generated normally can also exist inside a Matrix:
724
+
725
+ >>> from sympy import Matrix, MatrixSymbol
726
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
727
+ >>> A = MatrixSymbol('A', 3, 1)
728
+ >>> print(ccode(mat, A, standard='C89'))
729
+ A[0] = pow(x, 2);
730
+ if (x > 0) {
731
+ A[1] = x + 1;
732
+ }
733
+ else {
734
+ A[1] = x;
735
+ }
736
+ A[2] = sin(x);
737
+ """
738
+ from sympy.printing.c import c_code_printers
739
+ return c_code_printers[standard.lower()](settings).doprint(expr, assign_to)
740
+
741
+ def print_ccode(expr, **settings):
742
+ """Prints C representation of the given expression."""
743
+ print(ccode(expr, **settings))
744
+
745
+ def fcode(expr, assign_to=None, **settings):
746
+ """Converts an expr to a string of fortran code
747
+
748
+ Parameters
749
+ ==========
750
+
751
+ expr : Expr
752
+ A SymPy expression to be converted.
753
+ assign_to : optional
754
+ When given, the argument is used as the name of the variable to which
755
+ the expression is assigned. Can be a string, ``Symbol``,
756
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
757
+ line-wrapping, or for expressions that generate multi-line statements.
758
+ precision : integer, optional
759
+ DEPRECATED. Use type_mappings instead. The precision for numbers such
760
+ as pi [default=17].
761
+ user_functions : dict, optional
762
+ A dictionary where keys are ``FunctionClass`` instances and values are
763
+ their string representations. Alternatively, the dictionary value can
764
+ be a list of tuples i.e. [(argument_test, cfunction_string)]. See below
765
+ for examples.
766
+ human : bool, optional
767
+ If True, the result is a single string that may contain some constant
768
+ declarations for the number symbols. If False, the same information is
769
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
770
+ code_text). [default=True].
771
+ contract: bool, optional
772
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
773
+ rules and the corresponding nested loops over indices are generated.
774
+ Setting contract=False will not generate loops, instead the user is
775
+ responsible to provide values for the indices in the code.
776
+ [default=True].
777
+ source_format : optional
778
+ The source format can be either 'fixed' or 'free'. [default='fixed']
779
+ standard : integer, optional
780
+ The Fortran standard to be followed. This is specified as an integer.
781
+ Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77.
782
+ Note that currently the only distinction internally is between
783
+ standards before 95, and those 95 and after. This may change later as
784
+ more features are added.
785
+ name_mangling : bool, optional
786
+ If True, then the variables that would become identical in
787
+ case-insensitive Fortran are mangled by appending different number
788
+ of ``_`` at the end. If False, SymPy Will not interfere with naming of
789
+ variables. [default=True]
790
+
791
+ Examples
792
+ ========
793
+
794
+ >>> from sympy import fcode, symbols, Rational, sin, ceiling, floor
795
+ >>> x, tau = symbols("x, tau")
796
+ >>> fcode((2*tau)**Rational(7, 2))
797
+ ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)'
798
+ >>> fcode(sin(x), assign_to="s")
799
+ ' s = sin(x)'
800
+
801
+ Custom printing can be defined for certain types by passing a dictionary of
802
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
803
+ dictionary value can be a list of tuples i.e. [(argument_test,
804
+ cfunction_string)].
805
+
806
+ >>> custom_functions = {
807
+ ... "ceiling": "CEIL",
808
+ ... "floor": [(lambda x: not x.is_integer, "FLOOR1"),
809
+ ... (lambda x: x.is_integer, "FLOOR2")]
810
+ ... }
811
+ >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions)
812
+ ' CEIL(x) + FLOOR1(x)'
813
+
814
+ ``Piecewise`` expressions are converted into conditionals. If an
815
+ ``assign_to`` variable is provided an if statement is created, otherwise
816
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
817
+ default term, represented by ``(expr, True)`` then an error will be thrown.
818
+ This is to prevent generating an expression that may not evaluate to
819
+ anything.
820
+
821
+ >>> from sympy import Piecewise
822
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
823
+ >>> print(fcode(expr, tau))
824
+ if (x > 0) then
825
+ tau = x + 1
826
+ else
827
+ tau = x
828
+ end if
829
+
830
+ Support for loops is provided through ``Indexed`` types. With
831
+ ``contract=True`` these expressions will be turned into loops, whereas
832
+ ``contract=False`` will just print the assignment expression that should be
833
+ looped over:
834
+
835
+ >>> from sympy import Eq, IndexedBase, Idx
836
+ >>> len_y = 5
837
+ >>> y = IndexedBase('y', shape=(len_y,))
838
+ >>> t = IndexedBase('t', shape=(len_y,))
839
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
840
+ >>> i = Idx('i', len_y-1)
841
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
842
+ >>> fcode(e.rhs, assign_to=e.lhs, contract=False)
843
+ ' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))'
844
+
845
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
846
+ must be provided to ``assign_to``. Note that any expression that can be
847
+ generated normally can also exist inside a Matrix:
848
+
849
+ >>> from sympy import Matrix, MatrixSymbol
850
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
851
+ >>> A = MatrixSymbol('A', 3, 1)
852
+ >>> print(fcode(mat, A))
853
+ A(1, 1) = x**2
854
+ if (x > 0) then
855
+ A(2, 1) = x + 1
856
+ else
857
+ A(2, 1) = x
858
+ end if
859
+ A(3, 1) = sin(x)
860
+ """
861
+ from sympy.printing.fortran import FCodePrinter
862
+ return FCodePrinter(settings).doprint(expr, assign_to)
863
+
864
+
865
+ def print_fcode(expr, **settings):
866
+ """Prints the Fortran representation of the given expression.
867
+
868
+ See fcode for the meaning of the optional arguments.
869
+ """
870
+ print(fcode(expr, **settings))
871
+
872
+ def cxxcode(expr, assign_to=None, standard='c++11', **settings):
873
+ """ C++ equivalent of :func:`~.ccode`. """
874
+ from sympy.printing.cxx import cxx_code_printers
875
+ return cxx_code_printers[standard.lower()](settings).doprint(expr, assign_to)
env-llmeval/lib/python3.10/site-packages/sympy/printing/cxx.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ C++ code printer
3
+ """
4
+
5
+ from itertools import chain
6
+ from sympy.codegen.ast import Type, none
7
+ from .c import C89CodePrinter, C99CodePrinter
8
+
9
+ # These are defined in the other file so we can avoid importing sympy.codegen
10
+ # from the top-level 'import sympy'. Export them here as well.
11
+ from sympy.printing.codeprinter import cxxcode # noqa:F401
12
+
13
+ # from https://en.cppreference.com/w/cpp/keyword
14
+ reserved = {
15
+ 'C++98': [
16
+ 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break',
17
+ 'case', 'catch,', 'char', 'class', 'compl', 'const', 'const_cast',
18
+ 'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast',
19
+ 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float',
20
+ 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable',
21
+ 'namespace', 'new', 'not', 'not_eq', 'operator', 'or', 'or_eq',
22
+ 'private', 'protected', 'public', 'register', 'reinterpret_cast',
23
+ 'return', 'short', 'signed', 'sizeof', 'static', 'static_cast',
24
+ 'struct', 'switch', 'template', 'this', 'throw', 'true', 'try',
25
+ 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using',
26
+ 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq'
27
+ ]
28
+ }
29
+
30
+ reserved['C++11'] = reserved['C++98'][:] + [
31
+ 'alignas', 'alignof', 'char16_t', 'char32_t', 'constexpr', 'decltype',
32
+ 'noexcept', 'nullptr', 'static_assert', 'thread_local'
33
+ ]
34
+ reserved['C++17'] = reserved['C++11'][:]
35
+ reserved['C++17'].remove('register')
36
+ # TM TS: atomic_cancel, atomic_commit, atomic_noexcept, synchronized
37
+ # concepts TS: concept, requires
38
+ # module TS: import, module
39
+
40
+
41
+ _math_functions = {
42
+ 'C++98': {
43
+ 'Mod': 'fmod',
44
+ 'ceiling': 'ceil',
45
+ },
46
+ 'C++11': {
47
+ 'gamma': 'tgamma',
48
+ },
49
+ 'C++17': {
50
+ 'beta': 'beta',
51
+ 'Ei': 'expint',
52
+ 'zeta': 'riemann_zeta',
53
+ }
54
+ }
55
+
56
+ # from https://en.cppreference.com/w/cpp/header/cmath
57
+ for k in ('Abs', 'exp', 'log', 'log10', 'sqrt', 'sin', 'cos', 'tan', # 'Pow'
58
+ 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'floor'):
59
+ _math_functions['C++98'][k] = k.lower()
60
+
61
+
62
+ for k in ('asinh', 'acosh', 'atanh', 'erf', 'erfc'):
63
+ _math_functions['C++11'][k] = k.lower()
64
+
65
+
66
+ def _attach_print_method(cls, sympy_name, func_name):
67
+ meth_name = '_print_%s' % sympy_name
68
+ if hasattr(cls, meth_name):
69
+ raise ValueError("Edit method (or subclass) instead of overwriting.")
70
+ def _print_method(self, expr):
71
+ return '{}{}({})'.format(self._ns, func_name, ', '.join(map(self._print, expr.args)))
72
+ _print_method.__doc__ = "Prints code for %s" % k
73
+ setattr(cls, meth_name, _print_method)
74
+
75
+
76
+ def _attach_print_methods(cls, cont):
77
+ for sympy_name, cxx_name in cont[cls.standard].items():
78
+ _attach_print_method(cls, sympy_name, cxx_name)
79
+
80
+
81
+ class _CXXCodePrinterBase:
82
+ printmethod = "_cxxcode"
83
+ language = 'C++'
84
+ _ns = 'std::' # namespace
85
+
86
+ def __init__(self, settings=None):
87
+ super().__init__(settings or {})
88
+
89
+ def _print_Max(self, expr):
90
+ from sympy.functions.elementary.miscellaneous import Max
91
+ if len(expr.args) == 1:
92
+ return self._print(expr.args[0])
93
+ return "%smax(%s, %s)" % (self._ns, self._print(expr.args[0]),
94
+ self._print(Max(*expr.args[1:])))
95
+
96
+ def _print_Min(self, expr):
97
+ from sympy.functions.elementary.miscellaneous import Min
98
+ if len(expr.args) == 1:
99
+ return self._print(expr.args[0])
100
+ return "%smin(%s, %s)" % (self._ns, self._print(expr.args[0]),
101
+ self._print(Min(*expr.args[1:])))
102
+
103
+ def _print_using(self, expr):
104
+ if expr.alias == none:
105
+ return 'using %s' % expr.type
106
+ else:
107
+ raise ValueError("C++98 does not support type aliases")
108
+
109
+
110
+ class CXX98CodePrinter(_CXXCodePrinterBase, C89CodePrinter):
111
+ standard = 'C++98'
112
+ reserved_words = set(reserved['C++98'])
113
+
114
+
115
+ # _attach_print_methods(CXX98CodePrinter, _math_functions)
116
+
117
+
118
+ class CXX11CodePrinter(_CXXCodePrinterBase, C99CodePrinter):
119
+ standard = 'C++11'
120
+ reserved_words = set(reserved['C++11'])
121
+ type_mappings = dict(chain(
122
+ CXX98CodePrinter.type_mappings.items(),
123
+ {
124
+ Type('int8'): ('int8_t', {'cstdint'}),
125
+ Type('int16'): ('int16_t', {'cstdint'}),
126
+ Type('int32'): ('int32_t', {'cstdint'}),
127
+ Type('int64'): ('int64_t', {'cstdint'}),
128
+ Type('uint8'): ('uint8_t', {'cstdint'}),
129
+ Type('uint16'): ('uint16_t', {'cstdint'}),
130
+ Type('uint32'): ('uint32_t', {'cstdint'}),
131
+ Type('uint64'): ('uint64_t', {'cstdint'}),
132
+ Type('complex64'): ('std::complex<float>', {'complex'}),
133
+ Type('complex128'): ('std::complex<double>', {'complex'}),
134
+ Type('bool'): ('bool', None),
135
+ }.items()
136
+ ))
137
+
138
+ def _print_using(self, expr):
139
+ if expr.alias == none:
140
+ return super()._print_using(expr)
141
+ else:
142
+ return 'using %(alias)s = %(type)s' % expr.kwargs(apply=self._print)
143
+
144
+ # _attach_print_methods(CXX11CodePrinter, _math_functions)
145
+
146
+
147
+ class CXX17CodePrinter(_CXXCodePrinterBase, C99CodePrinter):
148
+ standard = 'C++17'
149
+ reserved_words = set(reserved['C++17'])
150
+
151
+ _kf = dict(C99CodePrinter._kf, **_math_functions['C++17'])
152
+
153
+ def _print_beta(self, expr):
154
+ return self._print_math_func(expr)
155
+
156
+ def _print_Ei(self, expr):
157
+ return self._print_math_func(expr)
158
+
159
+ def _print_zeta(self, expr):
160
+ return self._print_math_func(expr)
161
+
162
+
163
+ # _attach_print_methods(CXX17CodePrinter, _math_functions)
164
+
165
+ cxx_code_printers = {
166
+ 'c++98': CXX98CodePrinter,
167
+ 'c++11': CXX11CodePrinter,
168
+ 'c++17': CXX17CodePrinter
169
+ }
env-llmeval/lib/python3.10/site-packages/sympy/printing/defaults.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from sympy.core._print_helpers import Printable
2
+
3
+ # alias for compatibility
4
+ Printable.__module__ = __name__
5
+ DefaultPrinting = Printable
env-llmeval/lib/python3.10/site-packages/sympy/printing/fortran.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fortran code printer
3
+
4
+ The FCodePrinter converts single SymPy expressions into single Fortran
5
+ expressions, using the functions defined in the Fortran 77 standard where
6
+ possible. Some useful pointers to Fortran can be found on wikipedia:
7
+
8
+ https://en.wikipedia.org/wiki/Fortran
9
+
10
+ Most of the code below is based on the "Professional Programmer\'s Guide to
11
+ Fortran77" by Clive G. Page:
12
+
13
+ https://www.star.le.ac.uk/~cgp/prof77.html
14
+
15
+ Fortran is a case-insensitive language. This might cause trouble because
16
+ SymPy is case sensitive. So, fcode adds underscores to variable names when
17
+ it is necessary to make them different for Fortran.
18
+ """
19
+
20
+ from __future__ import annotations
21
+ from typing import Any
22
+
23
+ from collections import defaultdict
24
+ from itertools import chain
25
+ import string
26
+
27
+ from sympy.codegen.ast import (
28
+ Assignment, Declaration, Pointer, value_const,
29
+ float32, float64, float80, complex64, complex128, int8, int16, int32,
30
+ int64, intc, real, integer, bool_, complex_
31
+ )
32
+ from sympy.codegen.fnodes import (
33
+ allocatable, isign, dsign, cmplx, merge, literal_dp, elemental, pure,
34
+ intent_in, intent_out, intent_inout
35
+ )
36
+ from sympy.core import S, Add, N, Float, Symbol
37
+ from sympy.core.function import Function
38
+ from sympy.core.numbers import equal_valued
39
+ from sympy.core.relational import Eq
40
+ from sympy.sets import Range
41
+ from sympy.printing.codeprinter import CodePrinter
42
+ from sympy.printing.precedence import precedence, PRECEDENCE
43
+ from sympy.printing.printer import printer_context
44
+
45
+ # These are defined in the other file so we can avoid importing sympy.codegen
46
+ # from the top-level 'import sympy'. Export them here as well.
47
+ from sympy.printing.codeprinter import fcode, print_fcode # noqa:F401
48
+
49
+ known_functions = {
50
+ "sin": "sin",
51
+ "cos": "cos",
52
+ "tan": "tan",
53
+ "asin": "asin",
54
+ "acos": "acos",
55
+ "atan": "atan",
56
+ "atan2": "atan2",
57
+ "sinh": "sinh",
58
+ "cosh": "cosh",
59
+ "tanh": "tanh",
60
+ "log": "log",
61
+ "exp": "exp",
62
+ "erf": "erf",
63
+ "Abs": "abs",
64
+ "conjugate": "conjg",
65
+ "Max": "max",
66
+ "Min": "min",
67
+ }
68
+
69
+
70
+ class FCodePrinter(CodePrinter):
71
+ """A printer to convert SymPy expressions to strings of Fortran code"""
72
+ printmethod = "_fcode"
73
+ language = "Fortran"
74
+
75
+ type_aliases = {
76
+ integer: int32,
77
+ real: float64,
78
+ complex_: complex128,
79
+ }
80
+
81
+ type_mappings = {
82
+ intc: 'integer(c_int)',
83
+ float32: 'real*4', # real(kind(0.e0))
84
+ float64: 'real*8', # real(kind(0.d0))
85
+ float80: 'real*10', # real(kind(????))
86
+ complex64: 'complex*8',
87
+ complex128: 'complex*16',
88
+ int8: 'integer*1',
89
+ int16: 'integer*2',
90
+ int32: 'integer*4',
91
+ int64: 'integer*8',
92
+ bool_: 'logical'
93
+ }
94
+
95
+ type_modules = {
96
+ intc: {'iso_c_binding': 'c_int'}
97
+ }
98
+
99
+ _default_settings: dict[str, Any] = {
100
+ 'order': None,
101
+ 'full_prec': 'auto',
102
+ 'precision': 17,
103
+ 'user_functions': {},
104
+ 'human': True,
105
+ 'allow_unknown_functions': False,
106
+ 'source_format': 'fixed',
107
+ 'contract': True,
108
+ 'standard': 77,
109
+ 'name_mangling': True,
110
+ }
111
+
112
+ _operators = {
113
+ 'and': '.and.',
114
+ 'or': '.or.',
115
+ 'xor': '.neqv.',
116
+ 'equivalent': '.eqv.',
117
+ 'not': '.not. ',
118
+ }
119
+
120
+ _relationals = {
121
+ '!=': '/=',
122
+ }
123
+
124
+ def __init__(self, settings=None):
125
+ if not settings:
126
+ settings = {}
127
+ self.mangled_symbols = {} # Dict showing mapping of all words
128
+ self.used_name = []
129
+ self.type_aliases = dict(chain(self.type_aliases.items(),
130
+ settings.pop('type_aliases', {}).items()))
131
+ self.type_mappings = dict(chain(self.type_mappings.items(),
132
+ settings.pop('type_mappings', {}).items()))
133
+ super().__init__(settings)
134
+ self.known_functions = dict(known_functions)
135
+ userfuncs = settings.get('user_functions', {})
136
+ self.known_functions.update(userfuncs)
137
+ # leading columns depend on fixed or free format
138
+ standards = {66, 77, 90, 95, 2003, 2008}
139
+ if self._settings['standard'] not in standards:
140
+ raise ValueError("Unknown Fortran standard: %s" % self._settings[
141
+ 'standard'])
142
+ self.module_uses = defaultdict(set) # e.g.: use iso_c_binding, only: c_int
143
+
144
+ @property
145
+ def _lead(self):
146
+ if self._settings['source_format'] == 'fixed':
147
+ return {'code': " ", 'cont': " @ ", 'comment': "C "}
148
+ elif self._settings['source_format'] == 'free':
149
+ return {'code': "", 'cont': " ", 'comment': "! "}
150
+ else:
151
+ raise ValueError("Unknown source format: %s" % self._settings['source_format'])
152
+
153
+ def _print_Symbol(self, expr):
154
+ if self._settings['name_mangling'] == True:
155
+ if expr not in self.mangled_symbols:
156
+ name = expr.name
157
+ while name.lower() in self.used_name:
158
+ name += '_'
159
+ self.used_name.append(name.lower())
160
+ if name == expr.name:
161
+ self.mangled_symbols[expr] = expr
162
+ else:
163
+ self.mangled_symbols[expr] = Symbol(name)
164
+
165
+ expr = expr.xreplace(self.mangled_symbols)
166
+
167
+ name = super()._print_Symbol(expr)
168
+ return name
169
+
170
+ def _rate_index_position(self, p):
171
+ return -p*5
172
+
173
+ def _get_statement(self, codestring):
174
+ return codestring
175
+
176
+ def _get_comment(self, text):
177
+ return "! {}".format(text)
178
+
179
+ def _declare_number_const(self, name, value):
180
+ return "parameter ({} = {})".format(name, self._print(value))
181
+
182
+ def _print_NumberSymbol(self, expr):
183
+ # A Number symbol that is not implemented here or with _printmethod
184
+ # is registered and evaluated
185
+ self._number_symbols.add((expr, Float(expr.evalf(self._settings['precision']))))
186
+ return str(expr)
187
+
188
+ def _format_code(self, lines):
189
+ return self._wrap_fortran(self.indent_code(lines))
190
+
191
+ def _traverse_matrix_indices(self, mat):
192
+ rows, cols = mat.shape
193
+ return ((i, j) for j in range(cols) for i in range(rows))
194
+
195
+ def _get_loop_opening_ending(self, indices):
196
+ open_lines = []
197
+ close_lines = []
198
+ for i in indices:
199
+ # fortran arrays start at 1 and end at dimension
200
+ var, start, stop = map(self._print,
201
+ [i.label, i.lower + 1, i.upper + 1])
202
+ open_lines.append("do %s = %s, %s" % (var, start, stop))
203
+ close_lines.append("end do")
204
+ return open_lines, close_lines
205
+
206
+ def _print_sign(self, expr):
207
+ from sympy.functions.elementary.complexes import Abs
208
+ arg, = expr.args
209
+ if arg.is_integer:
210
+ new_expr = merge(0, isign(1, arg), Eq(arg, 0))
211
+ elif (arg.is_complex or arg.is_infinite):
212
+ new_expr = merge(cmplx(literal_dp(0), literal_dp(0)), arg/Abs(arg), Eq(Abs(arg), literal_dp(0)))
213
+ else:
214
+ new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg), Eq(arg, literal_dp(0)))
215
+ return self._print(new_expr)
216
+
217
+
218
+ def _print_Piecewise(self, expr):
219
+ if expr.args[-1].cond != True:
220
+ # We need the last conditional to be a True, otherwise the resulting
221
+ # function may not return a result.
222
+ raise ValueError("All Piecewise expressions must contain an "
223
+ "(expr, True) statement to be used as a default "
224
+ "condition. Without one, the generated "
225
+ "expression may not evaluate to anything under "
226
+ "some condition.")
227
+ lines = []
228
+ if expr.has(Assignment):
229
+ for i, (e, c) in enumerate(expr.args):
230
+ if i == 0:
231
+ lines.append("if (%s) then" % self._print(c))
232
+ elif i == len(expr.args) - 1 and c == True:
233
+ lines.append("else")
234
+ else:
235
+ lines.append("else if (%s) then" % self._print(c))
236
+ lines.append(self._print(e))
237
+ lines.append("end if")
238
+ return "\n".join(lines)
239
+ elif self._settings["standard"] >= 95:
240
+ # Only supported in F95 and newer:
241
+ # The piecewise was used in an expression, need to do inline
242
+ # operators. This has the downside that inline operators will
243
+ # not work for statements that span multiple lines (Matrix or
244
+ # Indexed expressions).
245
+ pattern = "merge({T}, {F}, {COND})"
246
+ code = self._print(expr.args[-1].expr)
247
+ terms = list(expr.args[:-1])
248
+ while terms:
249
+ e, c = terms.pop()
250
+ expr = self._print(e)
251
+ cond = self._print(c)
252
+ code = pattern.format(T=expr, F=code, COND=cond)
253
+ return code
254
+ else:
255
+ # `merge` is not supported prior to F95
256
+ raise NotImplementedError("Using Piecewise as an expression using "
257
+ "inline operators is not supported in "
258
+ "standards earlier than Fortran95.")
259
+
260
+ def _print_MatrixElement(self, expr):
261
+ return "{}({}, {})".format(self.parenthesize(expr.parent,
262
+ PRECEDENCE["Atom"], strict=True), expr.i + 1, expr.j + 1)
263
+
264
+ def _print_Add(self, expr):
265
+ # purpose: print complex numbers nicely in Fortran.
266
+ # collect the purely real and purely imaginary parts:
267
+ pure_real = []
268
+ pure_imaginary = []
269
+ mixed = []
270
+ for arg in expr.args:
271
+ if arg.is_number and arg.is_real:
272
+ pure_real.append(arg)
273
+ elif arg.is_number and arg.is_imaginary:
274
+ pure_imaginary.append(arg)
275
+ else:
276
+ mixed.append(arg)
277
+ if pure_imaginary:
278
+ if mixed:
279
+ PREC = precedence(expr)
280
+ term = Add(*mixed)
281
+ t = self._print(term)
282
+ if t.startswith('-'):
283
+ sign = "-"
284
+ t = t[1:]
285
+ else:
286
+ sign = "+"
287
+ if precedence(term) < PREC:
288
+ t = "(%s)" % t
289
+
290
+ return "cmplx(%s,%s) %s %s" % (
291
+ self._print(Add(*pure_real)),
292
+ self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
293
+ sign, t,
294
+ )
295
+ else:
296
+ return "cmplx(%s,%s)" % (
297
+ self._print(Add(*pure_real)),
298
+ self._print(-S.ImaginaryUnit*Add(*pure_imaginary)),
299
+ )
300
+ else:
301
+ return CodePrinter._print_Add(self, expr)
302
+
303
+ def _print_Function(self, expr):
304
+ # All constant function args are evaluated as floats
305
+ prec = self._settings['precision']
306
+ args = [N(a, prec) for a in expr.args]
307
+ eval_expr = expr.func(*args)
308
+ if not isinstance(eval_expr, Function):
309
+ return self._print(eval_expr)
310
+ else:
311
+ return CodePrinter._print_Function(self, expr.func(*args))
312
+
313
+ def _print_Mod(self, expr):
314
+ # NOTE : Fortran has the functions mod() and modulo(). modulo() behaves
315
+ # the same wrt to the sign of the arguments as Python and SymPy's
316
+ # modulus computations (% and Mod()) but is not available in Fortran 66
317
+ # or Fortran 77, thus we raise an error.
318
+ if self._settings['standard'] in [66, 77]:
319
+ msg = ("Python % operator and SymPy's Mod() function are not "
320
+ "supported by Fortran 66 or 77 standards.")
321
+ raise NotImplementedError(msg)
322
+ else:
323
+ x, y = expr.args
324
+ return " modulo({}, {})".format(self._print(x), self._print(y))
325
+
326
+ def _print_ImaginaryUnit(self, expr):
327
+ # purpose: print complex numbers nicely in Fortran.
328
+ return "cmplx(0,1)"
329
+
330
+ def _print_int(self, expr):
331
+ return str(expr)
332
+
333
+ def _print_Mul(self, expr):
334
+ # purpose: print complex numbers nicely in Fortran.
335
+ if expr.is_number and expr.is_imaginary:
336
+ return "cmplx(0,%s)" % (
337
+ self._print(-S.ImaginaryUnit*expr)
338
+ )
339
+ else:
340
+ return CodePrinter._print_Mul(self, expr)
341
+
342
+ def _print_Pow(self, expr):
343
+ PREC = precedence(expr)
344
+ if equal_valued(expr.exp, -1):
345
+ return '%s/%s' % (
346
+ self._print(literal_dp(1)),
347
+ self.parenthesize(expr.base, PREC)
348
+ )
349
+ elif equal_valued(expr.exp, 0.5):
350
+ if expr.base.is_integer:
351
+ # Fortran intrinsic sqrt() does not accept integer argument
352
+ if expr.base.is_Number:
353
+ return 'sqrt(%s.0d0)' % self._print(expr.base)
354
+ else:
355
+ return 'sqrt(dble(%s))' % self._print(expr.base)
356
+ else:
357
+ return 'sqrt(%s)' % self._print(expr.base)
358
+ else:
359
+ return CodePrinter._print_Pow(self, expr)
360
+
361
+ def _print_Rational(self, expr):
362
+ p, q = int(expr.p), int(expr.q)
363
+ return "%d.0d0/%d.0d0" % (p, q)
364
+
365
+ def _print_Float(self, expr):
366
+ printed = CodePrinter._print_Float(self, expr)
367
+ e = printed.find('e')
368
+ if e > -1:
369
+ return "%sd%s" % (printed[:e], printed[e + 1:])
370
+ return "%sd0" % printed
371
+
372
+ def _print_Relational(self, expr):
373
+ lhs_code = self._print(expr.lhs)
374
+ rhs_code = self._print(expr.rhs)
375
+ op = expr.rel_op
376
+ op = op if op not in self._relationals else self._relationals[op]
377
+ return "{} {} {}".format(lhs_code, op, rhs_code)
378
+
379
+ def _print_Indexed(self, expr):
380
+ inds = [ self._print(i) for i in expr.indices ]
381
+ return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
382
+
383
+ def _print_Idx(self, expr):
384
+ return self._print(expr.label)
385
+
386
+ def _print_AugmentedAssignment(self, expr):
387
+ lhs_code = self._print(expr.lhs)
388
+ rhs_code = self._print(expr.rhs)
389
+ return self._get_statement("{0} = {0} {1} {2}".format(
390
+ self._print(lhs_code), self._print(expr.binop), self._print(rhs_code)))
391
+
392
+ def _print_sum_(self, sm):
393
+ params = self._print(sm.array)
394
+ if sm.dim != None: # Must use '!= None', cannot use 'is not None'
395
+ params += ', ' + self._print(sm.dim)
396
+ if sm.mask != None: # Must use '!= None', cannot use 'is not None'
397
+ params += ', mask=' + self._print(sm.mask)
398
+ return '%s(%s)' % (sm.__class__.__name__.rstrip('_'), params)
399
+
400
+ def _print_product_(self, prod):
401
+ return self._print_sum_(prod)
402
+
403
+ def _print_Do(self, do):
404
+ excl = ['concurrent']
405
+ if do.step == 1:
406
+ excl.append('step')
407
+ step = ''
408
+ else:
409
+ step = ', {step}'
410
+
411
+ return (
412
+ 'do {concurrent}{counter} = {first}, {last}'+step+'\n'
413
+ '{body}\n'
414
+ 'end do\n'
415
+ ).format(
416
+ concurrent='concurrent ' if do.concurrent else '',
417
+ **do.kwargs(apply=lambda arg: self._print(arg), exclude=excl)
418
+ )
419
+
420
+ def _print_ImpliedDoLoop(self, idl):
421
+ step = '' if idl.step == 1 else ', {step}'
422
+ return ('({expr}, {counter} = {first}, {last}'+step+')').format(
423
+ **idl.kwargs(apply=lambda arg: self._print(arg))
424
+ )
425
+
426
+ def _print_For(self, expr):
427
+ target = self._print(expr.target)
428
+ if isinstance(expr.iterable, Range):
429
+ start, stop, step = expr.iterable.args
430
+ else:
431
+ raise NotImplementedError("Only iterable currently supported is Range")
432
+ body = self._print(expr.body)
433
+ return ('do {target} = {start}, {stop}, {step}\n'
434
+ '{body}\n'
435
+ 'end do').format(target=target, start=start, stop=stop - 1,
436
+ step=step, body=body)
437
+
438
+ def _print_Type(self, type_):
439
+ type_ = self.type_aliases.get(type_, type_)
440
+ type_str = self.type_mappings.get(type_, type_.name)
441
+ module_uses = self.type_modules.get(type_)
442
+ if module_uses:
443
+ for k, v in module_uses:
444
+ self.module_uses[k].add(v)
445
+ return type_str
446
+
447
+ def _print_Element(self, elem):
448
+ return '{symbol}({idxs})'.format(
449
+ symbol=self._print(elem.symbol),
450
+ idxs=', '.join((self._print(arg) for arg in elem.indices))
451
+ )
452
+
453
+ def _print_Extent(self, ext):
454
+ return str(ext)
455
+
456
+ def _print_Declaration(self, expr):
457
+ var = expr.variable
458
+ val = var.value
459
+ dim = var.attr_params('dimension')
460
+ intents = [intent in var.attrs for intent in (intent_in, intent_out, intent_inout)]
461
+ if intents.count(True) == 0:
462
+ intent = ''
463
+ elif intents.count(True) == 1:
464
+ intent = ', intent(%s)' % ['in', 'out', 'inout'][intents.index(True)]
465
+ else:
466
+ raise ValueError("Multiple intents specified for %s" % self)
467
+
468
+ if isinstance(var, Pointer):
469
+ raise NotImplementedError("Pointers are not available by default in Fortran.")
470
+ if self._settings["standard"] >= 90:
471
+ result = '{t}{vc}{dim}{intent}{alloc} :: {s}'.format(
472
+ t=self._print(var.type),
473
+ vc=', parameter' if value_const in var.attrs else '',
474
+ dim=', dimension(%s)' % ', '.join((self._print(arg) for arg in dim)) if dim else '',
475
+ intent=intent,
476
+ alloc=', allocatable' if allocatable in var.attrs else '',
477
+ s=self._print(var.symbol)
478
+ )
479
+ if val != None: # Must be "!= None", cannot be "is not None"
480
+ result += ' = %s' % self._print(val)
481
+ else:
482
+ if value_const in var.attrs or val:
483
+ raise NotImplementedError("F77 init./parameter statem. req. multiple lines.")
484
+ result = ' '.join((self._print(arg) for arg in [var.type, var.symbol]))
485
+
486
+ return result
487
+
488
+
489
+ def _print_Infinity(self, expr):
490
+ return '(huge(%s) + 1)' % self._print(literal_dp(0))
491
+
492
+ def _print_While(self, expr):
493
+ return 'do while ({condition})\n{body}\nend do'.format(**expr.kwargs(
494
+ apply=lambda arg: self._print(arg)))
495
+
496
+ def _print_BooleanTrue(self, expr):
497
+ return '.true.'
498
+
499
+ def _print_BooleanFalse(self, expr):
500
+ return '.false.'
501
+
502
+ def _pad_leading_columns(self, lines):
503
+ result = []
504
+ for line in lines:
505
+ if line.startswith('!'):
506
+ result.append(self._lead['comment'] + line[1:].lstrip())
507
+ else:
508
+ result.append(self._lead['code'] + line)
509
+ return result
510
+
511
+ def _wrap_fortran(self, lines):
512
+ """Wrap long Fortran lines
513
+
514
+ Argument:
515
+ lines -- a list of lines (without \\n character)
516
+
517
+ A comment line is split at white space. Code lines are split with a more
518
+ complex rule to give nice results.
519
+ """
520
+ # routine to find split point in a code line
521
+ my_alnum = set("_+-." + string.digits + string.ascii_letters)
522
+ my_white = set(" \t()")
523
+
524
+ def split_pos_code(line, endpos):
525
+ if len(line) <= endpos:
526
+ return len(line)
527
+ pos = endpos
528
+ split = lambda pos: \
529
+ (line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \
530
+ (line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \
531
+ (line[pos] in my_white and line[pos - 1] not in my_white) or \
532
+ (line[pos] not in my_white and line[pos - 1] in my_white)
533
+ while not split(pos):
534
+ pos -= 1
535
+ if pos == 0:
536
+ return endpos
537
+ return pos
538
+ # split line by line and add the split lines to result
539
+ result = []
540
+ if self._settings['source_format'] == 'free':
541
+ trailing = ' &'
542
+ else:
543
+ trailing = ''
544
+ for line in lines:
545
+ if line.startswith(self._lead['comment']):
546
+ # comment line
547
+ if len(line) > 72:
548
+ pos = line.rfind(" ", 6, 72)
549
+ if pos == -1:
550
+ pos = 72
551
+ hunk = line[:pos]
552
+ line = line[pos:].lstrip()
553
+ result.append(hunk)
554
+ while line:
555
+ pos = line.rfind(" ", 0, 66)
556
+ if pos == -1 or len(line) < 66:
557
+ pos = 66
558
+ hunk = line[:pos]
559
+ line = line[pos:].lstrip()
560
+ result.append("%s%s" % (self._lead['comment'], hunk))
561
+ else:
562
+ result.append(line)
563
+ elif line.startswith(self._lead['code']):
564
+ # code line
565
+ pos = split_pos_code(line, 72)
566
+ hunk = line[:pos].rstrip()
567
+ line = line[pos:].lstrip()
568
+ if line:
569
+ hunk += trailing
570
+ result.append(hunk)
571
+ while line:
572
+ pos = split_pos_code(line, 65)
573
+ hunk = line[:pos].rstrip()
574
+ line = line[pos:].lstrip()
575
+ if line:
576
+ hunk += trailing
577
+ result.append("%s%s" % (self._lead['cont'], hunk))
578
+ else:
579
+ result.append(line)
580
+ return result
581
+
582
+ def indent_code(self, code):
583
+ """Accepts a string of code or a list of code lines"""
584
+ if isinstance(code, str):
585
+ code_lines = self.indent_code(code.splitlines(True))
586
+ return ''.join(code_lines)
587
+
588
+ free = self._settings['source_format'] == 'free'
589
+ code = [ line.lstrip(' \t') for line in code ]
590
+
591
+ inc_keyword = ('do ', 'if(', 'if ', 'do\n', 'else', 'program', 'interface')
592
+ dec_keyword = ('end do', 'enddo', 'end if', 'endif', 'else', 'end program', 'end interface')
593
+
594
+ increase = [ int(any(map(line.startswith, inc_keyword)))
595
+ for line in code ]
596
+ decrease = [ int(any(map(line.startswith, dec_keyword)))
597
+ for line in code ]
598
+ continuation = [ int(any(map(line.endswith, ['&', '&\n'])))
599
+ for line in code ]
600
+
601
+ level = 0
602
+ cont_padding = 0
603
+ tabwidth = 3
604
+ new_code = []
605
+ for i, line in enumerate(code):
606
+ if line in ('', '\n'):
607
+ new_code.append(line)
608
+ continue
609
+ level -= decrease[i]
610
+
611
+ if free:
612
+ padding = " "*(level*tabwidth + cont_padding)
613
+ else:
614
+ padding = " "*level*tabwidth
615
+
616
+ line = "%s%s" % (padding, line)
617
+ if not free:
618
+ line = self._pad_leading_columns([line])[0]
619
+
620
+ new_code.append(line)
621
+
622
+ if continuation[i]:
623
+ cont_padding = 2*tabwidth
624
+ else:
625
+ cont_padding = 0
626
+ level += increase[i]
627
+
628
+ if not free:
629
+ return self._wrap_fortran(new_code)
630
+ return new_code
631
+
632
+ def _print_GoTo(self, goto):
633
+ if goto.expr: # computed goto
634
+ return "go to ({labels}), {expr}".format(
635
+ labels=', '.join((self._print(arg) for arg in goto.labels)),
636
+ expr=self._print(goto.expr)
637
+ )
638
+ else:
639
+ lbl, = goto.labels
640
+ return "go to %s" % self._print(lbl)
641
+
642
+ def _print_Program(self, prog):
643
+ return (
644
+ "program {name}\n"
645
+ "{body}\n"
646
+ "end program\n"
647
+ ).format(**prog.kwargs(apply=lambda arg: self._print(arg)))
648
+
649
+ def _print_Module(self, mod):
650
+ return (
651
+ "module {name}\n"
652
+ "{declarations}\n"
653
+ "\ncontains\n\n"
654
+ "{definitions}\n"
655
+ "end module\n"
656
+ ).format(**mod.kwargs(apply=lambda arg: self._print(arg)))
657
+
658
+ def _print_Stream(self, strm):
659
+ if strm.name == 'stdout' and self._settings["standard"] >= 2003:
660
+ self.module_uses['iso_c_binding'].add('stdint=>input_unit')
661
+ return 'input_unit'
662
+ elif strm.name == 'stderr' and self._settings["standard"] >= 2003:
663
+ self.module_uses['iso_c_binding'].add('stdint=>error_unit')
664
+ return 'error_unit'
665
+ else:
666
+ if strm.name == 'stdout':
667
+ return '*'
668
+ else:
669
+ return strm.name
670
+
671
+ def _print_Print(self, ps):
672
+ if ps.format_string != None: # Must be '!= None', cannot be 'is not None'
673
+ fmt = self._print(ps.format_string)
674
+ else:
675
+ fmt = "*"
676
+ return "print {fmt}, {iolist}".format(fmt=fmt, iolist=', '.join(
677
+ (self._print(arg) for arg in ps.print_args)))
678
+
679
+ def _print_Return(self, rs):
680
+ arg, = rs.args
681
+ return "{result_name} = {arg}".format(
682
+ result_name=self._context.get('result_name', 'sympy_result'),
683
+ arg=self._print(arg)
684
+ )
685
+
686
+ def _print_FortranReturn(self, frs):
687
+ arg, = frs.args
688
+ if arg:
689
+ return 'return %s' % self._print(arg)
690
+ else:
691
+ return 'return'
692
+
693
+ def _head(self, entity, fp, **kwargs):
694
+ bind_C_params = fp.attr_params('bind_C')
695
+ if bind_C_params is None:
696
+ bind = ''
697
+ else:
698
+ bind = ' bind(C, name="%s")' % bind_C_params[0] if bind_C_params else ' bind(C)'
699
+ result_name = self._settings.get('result_name', None)
700
+ return (
701
+ "{entity}{name}({arg_names}){result}{bind}\n"
702
+ "{arg_declarations}"
703
+ ).format(
704
+ entity=entity,
705
+ name=self._print(fp.name),
706
+ arg_names=', '.join([self._print(arg.symbol) for arg in fp.parameters]),
707
+ result=(' result(%s)' % result_name) if result_name else '',
708
+ bind=bind,
709
+ arg_declarations='\n'.join((self._print(Declaration(arg)) for arg in fp.parameters))
710
+ )
711
+
712
+ def _print_FunctionPrototype(self, fp):
713
+ entity = "{} function ".format(self._print(fp.return_type))
714
+ return (
715
+ "interface\n"
716
+ "{function_head}\n"
717
+ "end function\n"
718
+ "end interface"
719
+ ).format(function_head=self._head(entity, fp))
720
+
721
+ def _print_FunctionDefinition(self, fd):
722
+ if elemental in fd.attrs:
723
+ prefix = 'elemental '
724
+ elif pure in fd.attrs:
725
+ prefix = 'pure '
726
+ else:
727
+ prefix = ''
728
+
729
+ entity = "{} function ".format(self._print(fd.return_type))
730
+ with printer_context(self, result_name=fd.name):
731
+ return (
732
+ "{prefix}{function_head}\n"
733
+ "{body}\n"
734
+ "end function\n"
735
+ ).format(
736
+ prefix=prefix,
737
+ function_head=self._head(entity, fd),
738
+ body=self._print(fd.body)
739
+ )
740
+
741
+ def _print_Subroutine(self, sub):
742
+ return (
743
+ '{subroutine_head}\n'
744
+ '{body}\n'
745
+ 'end subroutine\n'
746
+ ).format(
747
+ subroutine_head=self._head('subroutine ', sub),
748
+ body=self._print(sub.body)
749
+ )
750
+
751
+ def _print_SubroutineCall(self, scall):
752
+ return 'call {name}({args})'.format(
753
+ name=self._print(scall.name),
754
+ args=', '.join((self._print(arg) for arg in scall.subroutine_args))
755
+ )
756
+
757
+ def _print_use_rename(self, rnm):
758
+ return "%s => %s" % tuple((self._print(arg) for arg in rnm.args))
759
+
760
+ def _print_use(self, use):
761
+ result = 'use %s' % self._print(use.namespace)
762
+ if use.rename != None: # Must be '!= None', cannot be 'is not None'
763
+ result += ', ' + ', '.join([self._print(rnm) for rnm in use.rename])
764
+ if use.only != None: # Must be '!= None', cannot be 'is not None'
765
+ result += ', only: ' + ', '.join([self._print(nly) for nly in use.only])
766
+ return result
767
+
768
+ def _print_BreakToken(self, _):
769
+ return 'exit'
770
+
771
+ def _print_ContinueToken(self, _):
772
+ return 'cycle'
773
+
774
+ def _print_ArrayConstructor(self, ac):
775
+ fmtstr = "[%s]" if self._settings["standard"] >= 2003 else '(/%s/)'
776
+ return fmtstr % ', '.join((self._print(arg) for arg in ac.elements))
777
+
778
+ def _print_ArrayElement(self, elem):
779
+ return '{symbol}({idxs})'.format(
780
+ symbol=self._print(elem.name),
781
+ idxs=', '.join((self._print(arg) for arg in elem.indices))
782
+ )
env-llmeval/lib/python3.10/site-packages/sympy/printing/glsl.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sympy.core import Basic, S
4
+ from sympy.core.function import Lambda
5
+ from sympy.core.numbers import equal_valued
6
+ from sympy.printing.codeprinter import CodePrinter
7
+ from sympy.printing.precedence import precedence
8
+ from functools import reduce
9
+
10
+ known_functions = {
11
+ 'Abs': 'abs',
12
+ 'sin': 'sin',
13
+ 'cos': 'cos',
14
+ 'tan': 'tan',
15
+ 'acos': 'acos',
16
+ 'asin': 'asin',
17
+ 'atan': 'atan',
18
+ 'atan2': 'atan',
19
+ 'ceiling': 'ceil',
20
+ 'floor': 'floor',
21
+ 'sign': 'sign',
22
+ 'exp': 'exp',
23
+ 'log': 'log',
24
+ 'add': 'add',
25
+ 'sub': 'sub',
26
+ 'mul': 'mul',
27
+ 'pow': 'pow'
28
+ }
29
+
30
+ class GLSLPrinter(CodePrinter):
31
+ """
32
+ Rudimentary, generic GLSL printing tools.
33
+
34
+ Additional settings:
35
+ 'use_operators': Boolean (should the printer use operators for +,-,*, or functions?)
36
+ """
37
+ _not_supported: set[Basic] = set()
38
+ printmethod = "_glsl"
39
+ language = "GLSL"
40
+
41
+ _default_settings = {
42
+ 'use_operators': True,
43
+ 'zero': 0,
44
+ 'mat_nested': False,
45
+ 'mat_separator': ',\n',
46
+ 'mat_transpose': False,
47
+ 'array_type': 'float',
48
+ 'glsl_types': True,
49
+
50
+ 'order': None,
51
+ 'full_prec': 'auto',
52
+ 'precision': 9,
53
+ 'user_functions': {},
54
+ 'human': True,
55
+ 'allow_unknown_functions': False,
56
+ 'contract': True,
57
+ 'error_on_reserved': False,
58
+ 'reserved_word_suffix': '_',
59
+ }
60
+
61
+ def __init__(self, settings={}):
62
+ CodePrinter.__init__(self, settings)
63
+ self.known_functions = dict(known_functions)
64
+ userfuncs = settings.get('user_functions', {})
65
+ self.known_functions.update(userfuncs)
66
+
67
+ def _rate_index_position(self, p):
68
+ return p*5
69
+
70
+ def _get_statement(self, codestring):
71
+ return "%s;" % codestring
72
+
73
+ def _get_comment(self, text):
74
+ return "// {}".format(text)
75
+
76
+ def _declare_number_const(self, name, value):
77
+ return "float {} = {};".format(name, value)
78
+
79
+ def _format_code(self, lines):
80
+ return self.indent_code(lines)
81
+
82
+ def indent_code(self, code):
83
+ """Accepts a string of code or a list of code lines"""
84
+
85
+ if isinstance(code, str):
86
+ code_lines = self.indent_code(code.splitlines(True))
87
+ return ''.join(code_lines)
88
+
89
+ tab = " "
90
+ inc_token = ('{', '(', '{\n', '(\n')
91
+ dec_token = ('}', ')')
92
+
93
+ code = [line.lstrip(' \t') for line in code]
94
+
95
+ increase = [int(any(map(line.endswith, inc_token))) for line in code]
96
+ decrease = [int(any(map(line.startswith, dec_token))) for line in code]
97
+
98
+ pretty = []
99
+ level = 0
100
+ for n, line in enumerate(code):
101
+ if line in ('', '\n'):
102
+ pretty.append(line)
103
+ continue
104
+ level -= decrease[n]
105
+ pretty.append("%s%s" % (tab*level, line))
106
+ level += increase[n]
107
+ return pretty
108
+
109
+ def _print_MatrixBase(self, mat):
110
+ mat_separator = self._settings['mat_separator']
111
+ mat_transpose = self._settings['mat_transpose']
112
+ column_vector = (mat.rows == 1) if mat_transpose else (mat.cols == 1)
113
+ A = mat.transpose() if mat_transpose != column_vector else mat
114
+
115
+ glsl_types = self._settings['glsl_types']
116
+ array_type = self._settings['array_type']
117
+ array_size = A.cols*A.rows
118
+ array_constructor = "{}[{}]".format(array_type, array_size)
119
+
120
+ if A.cols == 1:
121
+ return self._print(A[0]);
122
+ if A.rows <= 4 and A.cols <= 4 and glsl_types:
123
+ if A.rows == 1:
124
+ return "vec{}{}".format(
125
+ A.cols, A.table(self,rowstart='(',rowend=')')
126
+ )
127
+ elif A.rows == A.cols:
128
+ return "mat{}({})".format(
129
+ A.rows, A.table(self,rowsep=', ',
130
+ rowstart='',rowend='')
131
+ )
132
+ else:
133
+ return "mat{}x{}({})".format(
134
+ A.cols, A.rows,
135
+ A.table(self,rowsep=', ',
136
+ rowstart='',rowend='')
137
+ )
138
+ elif S.One in A.shape:
139
+ return "{}({})".format(
140
+ array_constructor,
141
+ A.table(self,rowsep=mat_separator,rowstart='',rowend='')
142
+ )
143
+ elif not self._settings['mat_nested']:
144
+ return "{}(\n{}\n) /* a {}x{} matrix */".format(
145
+ array_constructor,
146
+ A.table(self,rowsep=mat_separator,rowstart='',rowend=''),
147
+ A.rows, A.cols
148
+ )
149
+ elif self._settings['mat_nested']:
150
+ return "{}[{}][{}](\n{}\n)".format(
151
+ array_type, A.rows, A.cols,
152
+ A.table(self,rowsep=mat_separator,rowstart='float[](',rowend=')')
153
+ )
154
+
155
+ def _print_SparseRepMatrix(self, mat):
156
+ # do not allow sparse matrices to be made dense
157
+ return self._print_not_supported(mat)
158
+
159
+ def _traverse_matrix_indices(self, mat):
160
+ mat_transpose = self._settings['mat_transpose']
161
+ if mat_transpose:
162
+ rows,cols = mat.shape
163
+ else:
164
+ cols,rows = mat.shape
165
+ return ((i, j) for i in range(cols) for j in range(rows))
166
+
167
+ def _print_MatrixElement(self, expr):
168
+ # print('begin _print_MatrixElement')
169
+ nest = self._settings['mat_nested'];
170
+ glsl_types = self._settings['glsl_types'];
171
+ mat_transpose = self._settings['mat_transpose'];
172
+ if mat_transpose:
173
+ cols,rows = expr.parent.shape
174
+ i,j = expr.j,expr.i
175
+ else:
176
+ rows,cols = expr.parent.shape
177
+ i,j = expr.i,expr.j
178
+ pnt = self._print(expr.parent)
179
+ if glsl_types and ((rows <= 4 and cols <=4) or nest):
180
+ return "{}[{}][{}]".format(pnt, i, j)
181
+ else:
182
+ return "{}[{}]".format(pnt, i + j*rows)
183
+
184
+ def _print_list(self, expr):
185
+ l = ', '.join(self._print(item) for item in expr)
186
+ glsl_types = self._settings['glsl_types']
187
+ array_type = self._settings['array_type']
188
+ array_size = len(expr)
189
+ array_constructor = '{}[{}]'.format(array_type, array_size)
190
+
191
+ if array_size <= 4 and glsl_types:
192
+ return 'vec{}({})'.format(array_size, l)
193
+ else:
194
+ return '{}({})'.format(array_constructor, l)
195
+
196
+ _print_tuple = _print_list
197
+ _print_Tuple = _print_list
198
+
199
+ def _get_loop_opening_ending(self, indices):
200
+ open_lines = []
201
+ close_lines = []
202
+ loopstart = "for (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
203
+ for i in indices:
204
+ # GLSL arrays start at 0 and end at dimension-1
205
+ open_lines.append(loopstart % {
206
+ 'varble': self._print(i.label),
207
+ 'start': self._print(i.lower),
208
+ 'end': self._print(i.upper + 1)})
209
+ close_lines.append("}")
210
+ return open_lines, close_lines
211
+
212
+ def _print_Function_with_args(self, func, func_args):
213
+ if func in self.known_functions:
214
+ cond_func = self.known_functions[func]
215
+ func = None
216
+ if isinstance(cond_func, str):
217
+ func = cond_func
218
+ else:
219
+ for cond, func in cond_func:
220
+ if cond(func_args):
221
+ break
222
+ if func is not None:
223
+ try:
224
+ return func(*[self.parenthesize(item, 0) for item in func_args])
225
+ except TypeError:
226
+ return '{}({})'.format(func, self.stringify(func_args, ", "))
227
+ elif isinstance(func, Lambda):
228
+ # inlined function
229
+ return self._print(func(*func_args))
230
+ else:
231
+ return self._print_not_supported(func)
232
+
233
+ def _print_Piecewise(self, expr):
234
+ from sympy.codegen.ast import Assignment
235
+ if expr.args[-1].cond != True:
236
+ # We need the last conditional to be a True, otherwise the resulting
237
+ # function may not return a result.
238
+ raise ValueError("All Piecewise expressions must contain an "
239
+ "(expr, True) statement to be used as a default "
240
+ "condition. Without one, the generated "
241
+ "expression may not evaluate to anything under "
242
+ "some condition.")
243
+ lines = []
244
+ if expr.has(Assignment):
245
+ for i, (e, c) in enumerate(expr.args):
246
+ if i == 0:
247
+ lines.append("if (%s) {" % self._print(c))
248
+ elif i == len(expr.args) - 1 and c == True:
249
+ lines.append("else {")
250
+ else:
251
+ lines.append("else if (%s) {" % self._print(c))
252
+ code0 = self._print(e)
253
+ lines.append(code0)
254
+ lines.append("}")
255
+ return "\n".join(lines)
256
+ else:
257
+ # The piecewise was used in an expression, need to do inline
258
+ # operators. This has the downside that inline operators will
259
+ # not work for statements that span multiple lines (Matrix or
260
+ # Indexed expressions).
261
+ ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
262
+ self._print(e))
263
+ for e, c in expr.args[:-1]]
264
+ last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
265
+ return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
266
+
267
+ def _print_Idx(self, expr):
268
+ return self._print(expr.label)
269
+
270
+ def _print_Indexed(self, expr):
271
+ # calculate index for 1d array
272
+ dims = expr.shape
273
+ elem = S.Zero
274
+ offset = S.One
275
+ for i in reversed(range(expr.rank)):
276
+ elem += expr.indices[i]*offset
277
+ offset *= dims[i]
278
+ return "{}[{}]".format(
279
+ self._print(expr.base.label),
280
+ self._print(elem)
281
+ )
282
+
283
+ def _print_Pow(self, expr):
284
+ PREC = precedence(expr)
285
+ if equal_valued(expr.exp, -1):
286
+ return '1.0/%s' % (self.parenthesize(expr.base, PREC))
287
+ elif equal_valued(expr.exp, 0.5):
288
+ return 'sqrt(%s)' % self._print(expr.base)
289
+ else:
290
+ try:
291
+ e = self._print(float(expr.exp))
292
+ except TypeError:
293
+ e = self._print(expr.exp)
294
+ return self._print_Function_with_args('pow', (
295
+ self._print(expr.base),
296
+ e
297
+ ))
298
+
299
+ def _print_int(self, expr):
300
+ return str(float(expr))
301
+
302
+ def _print_Rational(self, expr):
303
+ return "{}.0/{}.0".format(expr.p, expr.q)
304
+
305
+ def _print_Relational(self, expr):
306
+ lhs_code = self._print(expr.lhs)
307
+ rhs_code = self._print(expr.rhs)
308
+ op = expr.rel_op
309
+ return "{} {} {}".format(lhs_code, op, rhs_code)
310
+
311
+ def _print_Add(self, expr, order=None):
312
+ if self._settings['use_operators']:
313
+ return CodePrinter._print_Add(self, expr, order=order)
314
+
315
+ terms = expr.as_ordered_terms()
316
+
317
+ def partition(p,l):
318
+ return reduce(lambda x, y: (x[0]+[y], x[1]) if p(y) else (x[0], x[1]+[y]), l, ([], []))
319
+ def add(a,b):
320
+ return self._print_Function_with_args('add', (a, b))
321
+ # return self.known_functions['add']+'(%s, %s)' % (a,b)
322
+ neg, pos = partition(lambda arg: arg.could_extract_minus_sign(), terms)
323
+ if pos:
324
+ s = pos = reduce(lambda a,b: add(a,b), (self._print(t) for t in pos))
325
+ else:
326
+ s = pos = self._print(self._settings['zero'])
327
+
328
+ if neg:
329
+ # sum the absolute values of the negative terms
330
+ neg = reduce(lambda a,b: add(a,b), (self._print(-n) for n in neg))
331
+ # then subtract them from the positive terms
332
+ s = self._print_Function_with_args('sub', (pos,neg))
333
+ # s = self.known_functions['sub']+'(%s, %s)' % (pos,neg)
334
+ return s
335
+
336
+ def _print_Mul(self, expr, **kwargs):
337
+ if self._settings['use_operators']:
338
+ return CodePrinter._print_Mul(self, expr, **kwargs)
339
+ terms = expr.as_ordered_factors()
340
+ def mul(a,b):
341
+ # return self.known_functions['mul']+'(%s, %s)' % (a,b)
342
+ return self._print_Function_with_args('mul', (a,b))
343
+
344
+ s = reduce(lambda a,b: mul(a,b), (self._print(t) for t in terms))
345
+ return s
346
+
347
+ def glsl_code(expr,assign_to=None,**settings):
348
+ """Converts an expr to a string of GLSL code
349
+
350
+ Parameters
351
+ ==========
352
+
353
+ expr : Expr
354
+ A SymPy expression to be converted.
355
+ assign_to : optional
356
+ When given, the argument is used for naming the variable or variables
357
+ to which the expression is assigned. Can be a string, ``Symbol``,
358
+ ``MatrixSymbol`` or ``Indexed`` type object. In cases where ``expr``
359
+ would be printed as an array, a list of string or ``Symbol`` objects
360
+ can also be passed.
361
+
362
+ This is helpful in case of line-wrapping, or for expressions that
363
+ generate multi-line statements. It can also be used to spread an array-like
364
+ expression into multiple assignments.
365
+ use_operators: bool, optional
366
+ If set to False, then *,/,+,- operators will be replaced with functions
367
+ mul, add, and sub, which must be implemented by the user, e.g. for
368
+ implementing non-standard rings or emulated quad/octal precision.
369
+ [default=True]
370
+ glsl_types: bool, optional
371
+ Set this argument to ``False`` in order to avoid using the ``vec`` and ``mat``
372
+ types. The printer will instead use arrays (or nested arrays).
373
+ [default=True]
374
+ mat_nested: bool, optional
375
+ GLSL version 4.3 and above support nested arrays (arrays of arrays). Set this to ``True``
376
+ to render matrices as nested arrays.
377
+ [default=False]
378
+ mat_separator: str, optional
379
+ By default, matrices are rendered with newlines using this separator,
380
+ making them easier to read, but less compact. By removing the newline
381
+ this option can be used to make them more vertically compact.
382
+ [default=',\n']
383
+ mat_transpose: bool, optional
384
+ GLSL's matrix multiplication implementation assumes column-major indexing.
385
+ By default, this printer ignores that convention. Setting this option to
386
+ ``True`` transposes all matrix output.
387
+ [default=False]
388
+ array_type: str, optional
389
+ The GLSL array constructor type.
390
+ [default='float']
391
+ precision : integer, optional
392
+ The precision for numbers such as pi [default=15].
393
+ user_functions : dict, optional
394
+ A dictionary where keys are ``FunctionClass`` instances and values are
395
+ their string representations. Alternatively, the dictionary value can
396
+ be a list of tuples i.e. [(argument_test, js_function_string)]. See
397
+ below for examples.
398
+ human : bool, optional
399
+ If True, the result is a single string that may contain some constant
400
+ declarations for the number symbols. If False, the same information is
401
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
402
+ code_text). [default=True].
403
+ contract: bool, optional
404
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
405
+ rules and the corresponding nested loops over indices are generated.
406
+ Setting contract=False will not generate loops, instead the user is
407
+ responsible to provide values for the indices in the code.
408
+ [default=True].
409
+
410
+ Examples
411
+ ========
412
+
413
+ >>> from sympy import glsl_code, symbols, Rational, sin, ceiling, Abs
414
+ >>> x, tau = symbols("x, tau")
415
+ >>> glsl_code((2*tau)**Rational(7, 2))
416
+ '8*sqrt(2)*pow(tau, 3.5)'
417
+ >>> glsl_code(sin(x), assign_to="float y")
418
+ 'float y = sin(x);'
419
+
420
+ Various GLSL types are supported:
421
+ >>> from sympy import Matrix, glsl_code
422
+ >>> glsl_code(Matrix([1,2,3]))
423
+ 'vec3(1, 2, 3)'
424
+
425
+ >>> glsl_code(Matrix([[1, 2],[3, 4]]))
426
+ 'mat2(1, 2, 3, 4)'
427
+
428
+ Pass ``mat_transpose = True`` to switch to column-major indexing:
429
+ >>> glsl_code(Matrix([[1, 2],[3, 4]]), mat_transpose = True)
430
+ 'mat2(1, 3, 2, 4)'
431
+
432
+ By default, larger matrices get collapsed into float arrays:
433
+ >>> print(glsl_code( Matrix([[1,2,3,4,5],[6,7,8,9,10]]) ))
434
+ float[10](
435
+ 1, 2, 3, 4, 5,
436
+ 6, 7, 8, 9, 10
437
+ ) /* a 2x5 matrix */
438
+
439
+ The type of array constructor used to print GLSL arrays can be controlled
440
+ via the ``array_type`` parameter:
441
+ >>> glsl_code(Matrix([1,2,3,4,5]), array_type='int')
442
+ 'int[5](1, 2, 3, 4, 5)'
443
+
444
+ Passing a list of strings or ``symbols`` to the ``assign_to`` parameter will yield
445
+ a multi-line assignment for each item in an array-like expression:
446
+ >>> x_struct_members = symbols('x.a x.b x.c x.d')
447
+ >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=x_struct_members))
448
+ x.a = 1;
449
+ x.b = 2;
450
+ x.c = 3;
451
+ x.d = 4;
452
+
453
+ This could be useful in cases where it's desirable to modify members of a
454
+ GLSL ``Struct``. It could also be used to spread items from an array-like
455
+ expression into various miscellaneous assignments:
456
+ >>> misc_assignments = ('x[0]', 'x[1]', 'float y', 'float z')
457
+ >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=misc_assignments))
458
+ x[0] = 1;
459
+ x[1] = 2;
460
+ float y = 3;
461
+ float z = 4;
462
+
463
+ Passing ``mat_nested = True`` instead prints out nested float arrays, which are
464
+ supported in GLSL 4.3 and above.
465
+ >>> mat = Matrix([
466
+ ... [ 0, 1, 2],
467
+ ... [ 3, 4, 5],
468
+ ... [ 6, 7, 8],
469
+ ... [ 9, 10, 11],
470
+ ... [12, 13, 14]])
471
+ >>> print(glsl_code( mat, mat_nested = True ))
472
+ float[5][3](
473
+ float[]( 0, 1, 2),
474
+ float[]( 3, 4, 5),
475
+ float[]( 6, 7, 8),
476
+ float[]( 9, 10, 11),
477
+ float[](12, 13, 14)
478
+ )
479
+
480
+
481
+
482
+ Custom printing can be defined for certain types by passing a dictionary of
483
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
484
+ dictionary value can be a list of tuples i.e. [(argument_test,
485
+ js_function_string)].
486
+
487
+ >>> custom_functions = {
488
+ ... "ceiling": "CEIL",
489
+ ... "Abs": [(lambda x: not x.is_integer, "fabs"),
490
+ ... (lambda x: x.is_integer, "ABS")]
491
+ ... }
492
+ >>> glsl_code(Abs(x) + ceiling(x), user_functions=custom_functions)
493
+ 'fabs(x) + CEIL(x)'
494
+
495
+ If further control is needed, addition, subtraction, multiplication and
496
+ division operators can be replaced with ``add``, ``sub``, and ``mul``
497
+ functions. This is done by passing ``use_operators = False``:
498
+
499
+ >>> x,y,z = symbols('x,y,z')
500
+ >>> glsl_code(x*(y+z), use_operators = False)
501
+ 'mul(x, add(y, z))'
502
+ >>> glsl_code(x*(y+z*(x-y)**z), use_operators = False)
503
+ 'mul(x, add(y, mul(z, pow(sub(x, y), z))))'
504
+
505
+ ``Piecewise`` expressions are converted into conditionals. If an
506
+ ``assign_to`` variable is provided an if statement is created, otherwise
507
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
508
+ default term, represented by ``(expr, True)`` then an error will be thrown.
509
+ This is to prevent generating an expression that may not evaluate to
510
+ anything.
511
+
512
+ >>> from sympy import Piecewise
513
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
514
+ >>> print(glsl_code(expr, tau))
515
+ if (x > 0) {
516
+ tau = x + 1;
517
+ }
518
+ else {
519
+ tau = x;
520
+ }
521
+
522
+ Support for loops is provided through ``Indexed`` types. With
523
+ ``contract=True`` these expressions will be turned into loops, whereas
524
+ ``contract=False`` will just print the assignment expression that should be
525
+ looped over:
526
+
527
+ >>> from sympy import Eq, IndexedBase, Idx
528
+ >>> len_y = 5
529
+ >>> y = IndexedBase('y', shape=(len_y,))
530
+ >>> t = IndexedBase('t', shape=(len_y,))
531
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
532
+ >>> i = Idx('i', len_y-1)
533
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
534
+ >>> glsl_code(e.rhs, assign_to=e.lhs, contract=False)
535
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
536
+
537
+ >>> from sympy import Matrix, MatrixSymbol
538
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
539
+ >>> A = MatrixSymbol('A', 3, 1)
540
+ >>> print(glsl_code(mat, A))
541
+ A[0][0] = pow(x, 2.0);
542
+ if (x > 0) {
543
+ A[1][0] = x + 1;
544
+ }
545
+ else {
546
+ A[1][0] = x;
547
+ }
548
+ A[2][0] = sin(x);
549
+ """
550
+ return GLSLPrinter(settings).doprint(expr,assign_to)
551
+
552
+ def print_glsl(expr, **settings):
553
+ """Prints the GLSL representation of the given expression.
554
+
555
+ See GLSLPrinter init function for settings.
556
+ """
557
+ print(glsl_code(expr, **settings))
env-llmeval/lib/python3.10/site-packages/sympy/printing/gtk.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.printing.mathml import mathml
2
+ from sympy.utilities.mathml import c2p
3
+ import tempfile
4
+ import subprocess
5
+
6
+
7
+ def print_gtk(x, start_viewer=True):
8
+ """Print to Gtkmathview, a gtk widget capable of rendering MathML.
9
+
10
+ Needs libgtkmathview-bin"""
11
+ with tempfile.NamedTemporaryFile('w') as file:
12
+ file.write(c2p(mathml(x), simple=True))
13
+ file.flush()
14
+
15
+ if start_viewer:
16
+ subprocess.check_call(('mathmlviewer', file.name))
env-llmeval/lib/python3.10/site-packages/sympy/printing/jscode.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Javascript code printer
3
+
4
+ The JavascriptCodePrinter converts single SymPy expressions into single
5
+ Javascript expressions, using the functions defined in the Javascript
6
+ Math object where possible.
7
+
8
+ """
9
+
10
+ from __future__ import annotations
11
+ from typing import Any
12
+
13
+ from sympy.core import S
14
+ from sympy.core.numbers import equal_valued
15
+ from sympy.printing.codeprinter import CodePrinter
16
+ from sympy.printing.precedence import precedence, PRECEDENCE
17
+
18
+
19
+ # dictionary mapping SymPy function to (argument_conditions, Javascript_function).
20
+ # Used in JavascriptCodePrinter._print_Function(self)
21
+ known_functions = {
22
+ 'Abs': 'Math.abs',
23
+ 'acos': 'Math.acos',
24
+ 'acosh': 'Math.acosh',
25
+ 'asin': 'Math.asin',
26
+ 'asinh': 'Math.asinh',
27
+ 'atan': 'Math.atan',
28
+ 'atan2': 'Math.atan2',
29
+ 'atanh': 'Math.atanh',
30
+ 'ceiling': 'Math.ceil',
31
+ 'cos': 'Math.cos',
32
+ 'cosh': 'Math.cosh',
33
+ 'exp': 'Math.exp',
34
+ 'floor': 'Math.floor',
35
+ 'log': 'Math.log',
36
+ 'Max': 'Math.max',
37
+ 'Min': 'Math.min',
38
+ 'sign': 'Math.sign',
39
+ 'sin': 'Math.sin',
40
+ 'sinh': 'Math.sinh',
41
+ 'tan': 'Math.tan',
42
+ 'tanh': 'Math.tanh',
43
+ }
44
+
45
+
46
+ class JavascriptCodePrinter(CodePrinter):
47
+ """"A Printer to convert Python expressions to strings of JavaScript code
48
+ """
49
+ printmethod = '_javascript'
50
+ language = 'JavaScript'
51
+
52
+ _default_settings: dict[str, Any] = {
53
+ 'order': None,
54
+ 'full_prec': 'auto',
55
+ 'precision': 17,
56
+ 'user_functions': {},
57
+ 'human': True,
58
+ 'allow_unknown_functions': False,
59
+ 'contract': True,
60
+ }
61
+
62
+ def __init__(self, settings={}):
63
+ CodePrinter.__init__(self, settings)
64
+ self.known_functions = dict(known_functions)
65
+ userfuncs = settings.get('user_functions', {})
66
+ self.known_functions.update(userfuncs)
67
+
68
+ def _rate_index_position(self, p):
69
+ return p*5
70
+
71
+ def _get_statement(self, codestring):
72
+ return "%s;" % codestring
73
+
74
+ def _get_comment(self, text):
75
+ return "// {}".format(text)
76
+
77
+ def _declare_number_const(self, name, value):
78
+ return "var {} = {};".format(name, value.evalf(self._settings['precision']))
79
+
80
+ def _format_code(self, lines):
81
+ return self.indent_code(lines)
82
+
83
+ def _traverse_matrix_indices(self, mat):
84
+ rows, cols = mat.shape
85
+ return ((i, j) for i in range(rows) for j in range(cols))
86
+
87
+ def _get_loop_opening_ending(self, indices):
88
+ open_lines = []
89
+ close_lines = []
90
+ loopstart = "for (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
91
+ for i in indices:
92
+ # Javascript arrays start at 0 and end at dimension-1
93
+ open_lines.append(loopstart % {
94
+ 'varble': self._print(i.label),
95
+ 'start': self._print(i.lower),
96
+ 'end': self._print(i.upper + 1)})
97
+ close_lines.append("}")
98
+ return open_lines, close_lines
99
+
100
+ def _print_Pow(self, expr):
101
+ PREC = precedence(expr)
102
+ if equal_valued(expr.exp, -1):
103
+ return '1/%s' % (self.parenthesize(expr.base, PREC))
104
+ elif equal_valued(expr.exp, 0.5):
105
+ return 'Math.sqrt(%s)' % self._print(expr.base)
106
+ elif expr.exp == S.One/3:
107
+ return 'Math.cbrt(%s)' % self._print(expr.base)
108
+ else:
109
+ return 'Math.pow(%s, %s)' % (self._print(expr.base),
110
+ self._print(expr.exp))
111
+
112
+ def _print_Rational(self, expr):
113
+ p, q = int(expr.p), int(expr.q)
114
+ return '%d/%d' % (p, q)
115
+
116
+ def _print_Mod(self, expr):
117
+ num, den = expr.args
118
+ PREC = precedence(expr)
119
+ snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
120
+ # % is remainder (same sign as numerator), not modulo (same sign as
121
+ # denominator), in js. Hence, % only works as modulo if both numbers
122
+ # have the same sign
123
+ if (num.is_nonnegative and den.is_nonnegative or
124
+ num.is_nonpositive and den.is_nonpositive):
125
+ return f"{snum} % {sden}"
126
+ return f"(({snum} % {sden}) + {sden}) % {sden}"
127
+
128
+ def _print_Relational(self, expr):
129
+ lhs_code = self._print(expr.lhs)
130
+ rhs_code = self._print(expr.rhs)
131
+ op = expr.rel_op
132
+ return "{} {} {}".format(lhs_code, op, rhs_code)
133
+
134
+ def _print_Indexed(self, expr):
135
+ # calculate index for 1d array
136
+ dims = expr.shape
137
+ elem = S.Zero
138
+ offset = S.One
139
+ for i in reversed(range(expr.rank)):
140
+ elem += expr.indices[i]*offset
141
+ offset *= dims[i]
142
+ return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
143
+
144
+ def _print_Idx(self, expr):
145
+ return self._print(expr.label)
146
+
147
+ def _print_Exp1(self, expr):
148
+ return "Math.E"
149
+
150
+ def _print_Pi(self, expr):
151
+ return 'Math.PI'
152
+
153
+ def _print_Infinity(self, expr):
154
+ return 'Number.POSITIVE_INFINITY'
155
+
156
+ def _print_NegativeInfinity(self, expr):
157
+ return 'Number.NEGATIVE_INFINITY'
158
+
159
+ def _print_Piecewise(self, expr):
160
+ from sympy.codegen.ast import Assignment
161
+ if expr.args[-1].cond != True:
162
+ # We need the last conditional to be a True, otherwise the resulting
163
+ # function may not return a result.
164
+ raise ValueError("All Piecewise expressions must contain an "
165
+ "(expr, True) statement to be used as a default "
166
+ "condition. Without one, the generated "
167
+ "expression may not evaluate to anything under "
168
+ "some condition.")
169
+ lines = []
170
+ if expr.has(Assignment):
171
+ for i, (e, c) in enumerate(expr.args):
172
+ if i == 0:
173
+ lines.append("if (%s) {" % self._print(c))
174
+ elif i == len(expr.args) - 1 and c == True:
175
+ lines.append("else {")
176
+ else:
177
+ lines.append("else if (%s) {" % self._print(c))
178
+ code0 = self._print(e)
179
+ lines.append(code0)
180
+ lines.append("}")
181
+ return "\n".join(lines)
182
+ else:
183
+ # The piecewise was used in an expression, need to do inline
184
+ # operators. This has the downside that inline operators will
185
+ # not work for statements that span multiple lines (Matrix or
186
+ # Indexed expressions).
187
+ ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e))
188
+ for e, c in expr.args[:-1]]
189
+ last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
190
+ return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
191
+
192
+ def _print_MatrixElement(self, expr):
193
+ return "{}[{}]".format(self.parenthesize(expr.parent,
194
+ PRECEDENCE["Atom"], strict=True),
195
+ expr.j + expr.i*expr.parent.shape[1])
196
+
197
+ def indent_code(self, code):
198
+ """Accepts a string of code or a list of code lines"""
199
+
200
+ if isinstance(code, str):
201
+ code_lines = self.indent_code(code.splitlines(True))
202
+ return ''.join(code_lines)
203
+
204
+ tab = " "
205
+ inc_token = ('{', '(', '{\n', '(\n')
206
+ dec_token = ('}', ')')
207
+
208
+ code = [ line.lstrip(' \t') for line in code ]
209
+
210
+ increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
211
+ decrease = [ int(any(map(line.startswith, dec_token)))
212
+ for line in code ]
213
+
214
+ pretty = []
215
+ level = 0
216
+ for n, line in enumerate(code):
217
+ if line in ('', '\n'):
218
+ pretty.append(line)
219
+ continue
220
+ level -= decrease[n]
221
+ pretty.append("%s%s" % (tab*level, line))
222
+ level += increase[n]
223
+ return pretty
224
+
225
+
226
+ def jscode(expr, assign_to=None, **settings):
227
+ """Converts an expr to a string of javascript code
228
+
229
+ Parameters
230
+ ==========
231
+
232
+ expr : Expr
233
+ A SymPy expression to be converted.
234
+ assign_to : optional
235
+ When given, the argument is used as the name of the variable to which
236
+ the expression is assigned. Can be a string, ``Symbol``,
237
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
238
+ line-wrapping, or for expressions that generate multi-line statements.
239
+ precision : integer, optional
240
+ The precision for numbers such as pi [default=15].
241
+ user_functions : dict, optional
242
+ A dictionary where keys are ``FunctionClass`` instances and values are
243
+ their string representations. Alternatively, the dictionary value can
244
+ be a list of tuples i.e. [(argument_test, js_function_string)]. See
245
+ below for examples.
246
+ human : bool, optional
247
+ If True, the result is a single string that may contain some constant
248
+ declarations for the number symbols. If False, the same information is
249
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
250
+ code_text). [default=True].
251
+ contract: bool, optional
252
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
253
+ rules and the corresponding nested loops over indices are generated.
254
+ Setting contract=False will not generate loops, instead the user is
255
+ responsible to provide values for the indices in the code.
256
+ [default=True].
257
+
258
+ Examples
259
+ ========
260
+
261
+ >>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs
262
+ >>> x, tau = symbols("x, tau")
263
+ >>> jscode((2*tau)**Rational(7, 2))
264
+ '8*Math.sqrt(2)*Math.pow(tau, 7/2)'
265
+ >>> jscode(sin(x), assign_to="s")
266
+ 's = Math.sin(x);'
267
+
268
+ Custom printing can be defined for certain types by passing a dictionary of
269
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
270
+ dictionary value can be a list of tuples i.e. [(argument_test,
271
+ js_function_string)].
272
+
273
+ >>> custom_functions = {
274
+ ... "ceiling": "CEIL",
275
+ ... "Abs": [(lambda x: not x.is_integer, "fabs"),
276
+ ... (lambda x: x.is_integer, "ABS")]
277
+ ... }
278
+ >>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions)
279
+ 'fabs(x) + CEIL(x)'
280
+
281
+ ``Piecewise`` expressions are converted into conditionals. If an
282
+ ``assign_to`` variable is provided an if statement is created, otherwise
283
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
284
+ default term, represented by ``(expr, True)`` then an error will be thrown.
285
+ This is to prevent generating an expression that may not evaluate to
286
+ anything.
287
+
288
+ >>> from sympy import Piecewise
289
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
290
+ >>> print(jscode(expr, tau))
291
+ if (x > 0) {
292
+ tau = x + 1;
293
+ }
294
+ else {
295
+ tau = x;
296
+ }
297
+
298
+ Support for loops is provided through ``Indexed`` types. With
299
+ ``contract=True`` these expressions will be turned into loops, whereas
300
+ ``contract=False`` will just print the assignment expression that should be
301
+ looped over:
302
+
303
+ >>> from sympy import Eq, IndexedBase, Idx
304
+ >>> len_y = 5
305
+ >>> y = IndexedBase('y', shape=(len_y,))
306
+ >>> t = IndexedBase('t', shape=(len_y,))
307
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
308
+ >>> i = Idx('i', len_y-1)
309
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
310
+ >>> jscode(e.rhs, assign_to=e.lhs, contract=False)
311
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
312
+
313
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
314
+ must be provided to ``assign_to``. Note that any expression that can be
315
+ generated normally can also exist inside a Matrix:
316
+
317
+ >>> from sympy import Matrix, MatrixSymbol
318
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
319
+ >>> A = MatrixSymbol('A', 3, 1)
320
+ >>> print(jscode(mat, A))
321
+ A[0] = Math.pow(x, 2);
322
+ if (x > 0) {
323
+ A[1] = x + 1;
324
+ }
325
+ else {
326
+ A[1] = x;
327
+ }
328
+ A[2] = Math.sin(x);
329
+ """
330
+
331
+ return JavascriptCodePrinter(settings).doprint(expr, assign_to)
332
+
333
+
334
+ def print_jscode(expr, **settings):
335
+ """Prints the Javascript representation of the given expression.
336
+
337
+ See jscode for the meaning of the optional arguments.
338
+ """
339
+ print(jscode(expr, **settings))
env-llmeval/lib/python3.10/site-packages/sympy/printing/julia.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Julia code printer
3
+
4
+ The `JuliaCodePrinter` converts SymPy expressions into Julia expressions.
5
+
6
+ A complete code generator, which uses `julia_code` extensively, can be found
7
+ in `sympy.utilities.codegen`. The `codegen` module can be used to generate
8
+ complete source code files.
9
+
10
+ """
11
+
12
+ from __future__ import annotations
13
+ from typing import Any
14
+
15
+ from sympy.core import Mul, Pow, S, Rational
16
+ from sympy.core.mul import _keep_coeff
17
+ from sympy.core.numbers import equal_valued
18
+ from sympy.printing.codeprinter import CodePrinter
19
+ from sympy.printing.precedence import precedence, PRECEDENCE
20
+ from re import search
21
+
22
+ # List of known functions. First, those that have the same name in
23
+ # SymPy and Julia. This is almost certainly incomplete!
24
+ known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
25
+ "asin", "acos", "atan", "acot", "asec", "acsc",
26
+ "sinh", "cosh", "tanh", "coth", "sech", "csch",
27
+ "asinh", "acosh", "atanh", "acoth", "asech", "acsch",
28
+ "sinc", "atan2", "sign", "floor", "log", "exp",
29
+ "cbrt", "sqrt", "erf", "erfc", "erfi",
30
+ "factorial", "gamma", "digamma", "trigamma",
31
+ "polygamma", "beta",
32
+ "airyai", "airyaiprime", "airybi", "airybiprime",
33
+ "besselj", "bessely", "besseli", "besselk",
34
+ "erfinv", "erfcinv"]
35
+ # These functions have different names ("SymPy": "Julia"), more
36
+ # generally a mapping to (argument_conditions, julia_function).
37
+ known_fcns_src2 = {
38
+ "Abs": "abs",
39
+ "ceiling": "ceil",
40
+ "conjugate": "conj",
41
+ "hankel1": "hankelh1",
42
+ "hankel2": "hankelh2",
43
+ "im": "imag",
44
+ "re": "real"
45
+ }
46
+
47
+
48
+ class JuliaCodePrinter(CodePrinter):
49
+ """
50
+ A printer to convert expressions to strings of Julia code.
51
+ """
52
+ printmethod = "_julia"
53
+ language = "Julia"
54
+
55
+ _operators = {
56
+ 'and': '&&',
57
+ 'or': '||',
58
+ 'not': '!',
59
+ }
60
+
61
+ _default_settings: dict[str, Any] = {
62
+ 'order': None,
63
+ 'full_prec': 'auto',
64
+ 'precision': 17,
65
+ 'user_functions': {},
66
+ 'human': True,
67
+ 'allow_unknown_functions': False,
68
+ 'contract': True,
69
+ 'inline': True,
70
+ }
71
+ # Note: contract is for expressing tensors as loops (if True), or just
72
+ # assignment (if False). FIXME: this should be looked a more carefully
73
+ # for Julia.
74
+
75
+ def __init__(self, settings={}):
76
+ super().__init__(settings)
77
+ self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
78
+ self.known_functions.update(dict(known_fcns_src2))
79
+ userfuncs = settings.get('user_functions', {})
80
+ self.known_functions.update(userfuncs)
81
+
82
+
83
+ def _rate_index_position(self, p):
84
+ return p*5
85
+
86
+
87
+ def _get_statement(self, codestring):
88
+ return "%s" % codestring
89
+
90
+
91
+ def _get_comment(self, text):
92
+ return "# {}".format(text)
93
+
94
+
95
+ def _declare_number_const(self, name, value):
96
+ return "const {} = {}".format(name, value)
97
+
98
+
99
+ def _format_code(self, lines):
100
+ return self.indent_code(lines)
101
+
102
+
103
+ def _traverse_matrix_indices(self, mat):
104
+ # Julia uses Fortran order (column-major)
105
+ rows, cols = mat.shape
106
+ return ((i, j) for j in range(cols) for i in range(rows))
107
+
108
+
109
+ def _get_loop_opening_ending(self, indices):
110
+ open_lines = []
111
+ close_lines = []
112
+ for i in indices:
113
+ # Julia arrays start at 1 and end at dimension
114
+ var, start, stop = map(self._print,
115
+ [i.label, i.lower + 1, i.upper + 1])
116
+ open_lines.append("for %s = %s:%s" % (var, start, stop))
117
+ close_lines.append("end")
118
+ return open_lines, close_lines
119
+
120
+
121
+ def _print_Mul(self, expr):
122
+ # print complex numbers nicely in Julia
123
+ if (expr.is_number and expr.is_imaginary and
124
+ expr.as_coeff_Mul()[0].is_integer):
125
+ return "%sim" % self._print(-S.ImaginaryUnit*expr)
126
+
127
+ # cribbed from str.py
128
+ prec = precedence(expr)
129
+
130
+ c, e = expr.as_coeff_Mul()
131
+ if c < 0:
132
+ expr = _keep_coeff(-c, e)
133
+ sign = "-"
134
+ else:
135
+ sign = ""
136
+
137
+ a = [] # items in the numerator
138
+ b = [] # items that are in the denominator (if any)
139
+
140
+ pow_paren = [] # Will collect all pow with more than one base element and exp = -1
141
+
142
+ if self.order not in ('old', 'none'):
143
+ args = expr.as_ordered_factors()
144
+ else:
145
+ # use make_args in case expr was something like -x -> x
146
+ args = Mul.make_args(expr)
147
+
148
+ # Gather args for numerator/denominator
149
+ for item in args:
150
+ if (item.is_commutative and item.is_Pow and item.exp.is_Rational
151
+ and item.exp.is_negative):
152
+ if item.exp != -1:
153
+ b.append(Pow(item.base, -item.exp, evaluate=False))
154
+ else:
155
+ if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
156
+ pow_paren.append(item)
157
+ b.append(Pow(item.base, -item.exp))
158
+ elif item.is_Rational and item is not S.Infinity and item.p == 1:
159
+ # Save the Rational type in julia Unless the numerator is 1.
160
+ # For example:
161
+ # julia_code(Rational(3, 7)*x) --> (3 // 7) * x
162
+ # julia_code(x/3) --> x / 3 but not x * (1 // 3)
163
+ b.append(Rational(item.q))
164
+ else:
165
+ a.append(item)
166
+
167
+ a = a or [S.One]
168
+
169
+ a_str = [self.parenthesize(x, prec) for x in a]
170
+ b_str = [self.parenthesize(x, prec) for x in b]
171
+
172
+ # To parenthesize Pow with exp = -1 and having more than one Symbol
173
+ for item in pow_paren:
174
+ if item.base in b:
175
+ b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
176
+
177
+ # from here it differs from str.py to deal with "*" and ".*"
178
+ def multjoin(a, a_str):
179
+ # here we probably are assuming the constants will come first
180
+ r = a_str[0]
181
+ for i in range(1, len(a)):
182
+ mulsym = '*' if a[i-1].is_number else '.*'
183
+ r = "%s %s %s" % (r, mulsym, a_str[i])
184
+ return r
185
+
186
+ if not b:
187
+ return sign + multjoin(a, a_str)
188
+ elif len(b) == 1:
189
+ divsym = '/' if b[0].is_number else './'
190
+ return "%s %s %s" % (sign+multjoin(a, a_str), divsym, b_str[0])
191
+ else:
192
+ divsym = '/' if all(bi.is_number for bi in b) else './'
193
+ return "%s %s (%s)" % (sign + multjoin(a, a_str), divsym, multjoin(b, b_str))
194
+
195
+ def _print_Relational(self, expr):
196
+ lhs_code = self._print(expr.lhs)
197
+ rhs_code = self._print(expr.rhs)
198
+ op = expr.rel_op
199
+ return "{} {} {}".format(lhs_code, op, rhs_code)
200
+
201
+ def _print_Pow(self, expr):
202
+ powsymbol = '^' if all(x.is_number for x in expr.args) else '.^'
203
+
204
+ PREC = precedence(expr)
205
+
206
+ if equal_valued(expr.exp, 0.5):
207
+ return "sqrt(%s)" % self._print(expr.base)
208
+
209
+ if expr.is_commutative:
210
+ if equal_valued(expr.exp, -0.5):
211
+ sym = '/' if expr.base.is_number else './'
212
+ return "1 %s sqrt(%s)" % (sym, self._print(expr.base))
213
+ if equal_valued(expr.exp, -1):
214
+ sym = '/' if expr.base.is_number else './'
215
+ return "1 %s %s" % (sym, self.parenthesize(expr.base, PREC))
216
+
217
+ return '%s %s %s' % (self.parenthesize(expr.base, PREC), powsymbol,
218
+ self.parenthesize(expr.exp, PREC))
219
+
220
+
221
+ def _print_MatPow(self, expr):
222
+ PREC = precedence(expr)
223
+ return '%s ^ %s' % (self.parenthesize(expr.base, PREC),
224
+ self.parenthesize(expr.exp, PREC))
225
+
226
+
227
+ def _print_Pi(self, expr):
228
+ if self._settings["inline"]:
229
+ return "pi"
230
+ else:
231
+ return super()._print_NumberSymbol(expr)
232
+
233
+
234
+ def _print_ImaginaryUnit(self, expr):
235
+ return "im"
236
+
237
+
238
+ def _print_Exp1(self, expr):
239
+ if self._settings["inline"]:
240
+ return "e"
241
+ else:
242
+ return super()._print_NumberSymbol(expr)
243
+
244
+
245
+ def _print_EulerGamma(self, expr):
246
+ if self._settings["inline"]:
247
+ return "eulergamma"
248
+ else:
249
+ return super()._print_NumberSymbol(expr)
250
+
251
+
252
+ def _print_Catalan(self, expr):
253
+ if self._settings["inline"]:
254
+ return "catalan"
255
+ else:
256
+ return super()._print_NumberSymbol(expr)
257
+
258
+
259
+ def _print_GoldenRatio(self, expr):
260
+ if self._settings["inline"]:
261
+ return "golden"
262
+ else:
263
+ return super()._print_NumberSymbol(expr)
264
+
265
+
266
+ def _print_Assignment(self, expr):
267
+ from sympy.codegen.ast import Assignment
268
+ from sympy.functions.elementary.piecewise import Piecewise
269
+ from sympy.tensor.indexed import IndexedBase
270
+ # Copied from codeprinter, but remove special MatrixSymbol treatment
271
+ lhs = expr.lhs
272
+ rhs = expr.rhs
273
+ # We special case assignments that take multiple lines
274
+ if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
275
+ # Here we modify Piecewise so each expression is now
276
+ # an Assignment, and then continue on the print.
277
+ expressions = []
278
+ conditions = []
279
+ for (e, c) in rhs.args:
280
+ expressions.append(Assignment(lhs, e))
281
+ conditions.append(c)
282
+ temp = Piecewise(*zip(expressions, conditions))
283
+ return self._print(temp)
284
+ if self._settings["contract"] and (lhs.has(IndexedBase) or
285
+ rhs.has(IndexedBase)):
286
+ # Here we check if there is looping to be done, and if so
287
+ # print the required loops.
288
+ return self._doprint_loops(rhs, lhs)
289
+ else:
290
+ lhs_code = self._print(lhs)
291
+ rhs_code = self._print(rhs)
292
+ return self._get_statement("%s = %s" % (lhs_code, rhs_code))
293
+
294
+
295
+ def _print_Infinity(self, expr):
296
+ return 'Inf'
297
+
298
+
299
+ def _print_NegativeInfinity(self, expr):
300
+ return '-Inf'
301
+
302
+
303
+ def _print_NaN(self, expr):
304
+ return 'NaN'
305
+
306
+
307
+ def _print_list(self, expr):
308
+ return 'Any[' + ', '.join(self._print(a) for a in expr) + ']'
309
+
310
+
311
+ def _print_tuple(self, expr):
312
+ if len(expr) == 1:
313
+ return "(%s,)" % self._print(expr[0])
314
+ else:
315
+ return "(%s)" % self.stringify(expr, ", ")
316
+ _print_Tuple = _print_tuple
317
+
318
+
319
+ def _print_BooleanTrue(self, expr):
320
+ return "true"
321
+
322
+
323
+ def _print_BooleanFalse(self, expr):
324
+ return "false"
325
+
326
+
327
+ def _print_bool(self, expr):
328
+ return str(expr).lower()
329
+
330
+
331
+ # Could generate quadrature code for definite Integrals?
332
+ #_print_Integral = _print_not_supported
333
+
334
+
335
+ def _print_MatrixBase(self, A):
336
+ # Handle zero dimensions:
337
+ if S.Zero in A.shape:
338
+ return 'zeros(%s, %s)' % (A.rows, A.cols)
339
+ elif (A.rows, A.cols) == (1, 1):
340
+ return "[%s]" % A[0, 0]
341
+ elif A.rows == 1:
342
+ return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ')
343
+ elif A.cols == 1:
344
+ # note .table would unnecessarily equispace the rows
345
+ return "[%s]" % ", ".join([self._print(a) for a in A])
346
+ return "[%s]" % A.table(self, rowstart='', rowend='',
347
+ rowsep=';\n', colsep=' ')
348
+
349
+
350
+ def _print_SparseRepMatrix(self, A):
351
+ from sympy.matrices import Matrix
352
+ L = A.col_list();
353
+ # make row vectors of the indices and entries
354
+ I = Matrix([k[0] + 1 for k in L])
355
+ J = Matrix([k[1] + 1 for k in L])
356
+ AIJ = Matrix([k[2] for k in L])
357
+ return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
358
+ self._print(AIJ), A.rows, A.cols)
359
+
360
+
361
+ def _print_MatrixElement(self, expr):
362
+ return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
363
+ + '[%s,%s]' % (expr.i + 1, expr.j + 1)
364
+
365
+
366
+ def _print_MatrixSlice(self, expr):
367
+ def strslice(x, lim):
368
+ l = x[0] + 1
369
+ h = x[1]
370
+ step = x[2]
371
+ lstr = self._print(l)
372
+ hstr = 'end' if h == lim else self._print(h)
373
+ if step == 1:
374
+ if l == 1 and h == lim:
375
+ return ':'
376
+ if l == h:
377
+ return lstr
378
+ else:
379
+ return lstr + ':' + hstr
380
+ else:
381
+ return ':'.join((lstr, self._print(step), hstr))
382
+ return (self._print(expr.parent) + '[' +
383
+ strslice(expr.rowslice, expr.parent.shape[0]) + ',' +
384
+ strslice(expr.colslice, expr.parent.shape[1]) + ']')
385
+
386
+
387
+ def _print_Indexed(self, expr):
388
+ inds = [ self._print(i) for i in expr.indices ]
389
+ return "%s[%s]" % (self._print(expr.base.label), ",".join(inds))
390
+
391
+
392
+ def _print_Idx(self, expr):
393
+ return self._print(expr.label)
394
+
395
+
396
+ def _print_Identity(self, expr):
397
+ return "eye(%s)" % self._print(expr.shape[0])
398
+
399
+ def _print_HadamardProduct(self, expr):
400
+ return ' .* '.join([self.parenthesize(arg, precedence(expr))
401
+ for arg in expr.args])
402
+
403
+ def _print_HadamardPower(self, expr):
404
+ PREC = precedence(expr)
405
+ return '.**'.join([
406
+ self.parenthesize(expr.base, PREC),
407
+ self.parenthesize(expr.exp, PREC)
408
+ ])
409
+
410
+ def _print_Rational(self, expr):
411
+ if expr.q == 1:
412
+ return str(expr.p)
413
+ return "%s // %s" % (expr.p, expr.q)
414
+
415
+ # Note: as of 2022, Julia doesn't have spherical Bessel functions
416
+ def _print_jn(self, expr):
417
+ from sympy.functions import sqrt, besselj
418
+ x = expr.argument
419
+ expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
420
+ return self._print(expr2)
421
+
422
+
423
+ def _print_yn(self, expr):
424
+ from sympy.functions import sqrt, bessely
425
+ x = expr.argument
426
+ expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
427
+ return self._print(expr2)
428
+
429
+
430
+ def _print_Piecewise(self, expr):
431
+ if expr.args[-1].cond != True:
432
+ # We need the last conditional to be a True, otherwise the resulting
433
+ # function may not return a result.
434
+ raise ValueError("All Piecewise expressions must contain an "
435
+ "(expr, True) statement to be used as a default "
436
+ "condition. Without one, the generated "
437
+ "expression may not evaluate to anything under "
438
+ "some condition.")
439
+ lines = []
440
+ if self._settings["inline"]:
441
+ # Express each (cond, expr) pair in a nested Horner form:
442
+ # (condition) .* (expr) + (not cond) .* (<others>)
443
+ # Expressions that result in multiple statements won't work here.
444
+ ecpairs = ["({}) ? ({}) :".format
445
+ (self._print(c), self._print(e))
446
+ for e, c in expr.args[:-1]]
447
+ elast = " (%s)" % self._print(expr.args[-1].expr)
448
+ pw = "\n".join(ecpairs) + elast
449
+ # Note: current need these outer brackets for 2*pw. Would be
450
+ # nicer to teach parenthesize() to do this for us when needed!
451
+ return "(" + pw + ")"
452
+ else:
453
+ for i, (e, c) in enumerate(expr.args):
454
+ if i == 0:
455
+ lines.append("if (%s)" % self._print(c))
456
+ elif i == len(expr.args) - 1 and c == True:
457
+ lines.append("else")
458
+ else:
459
+ lines.append("elseif (%s)" % self._print(c))
460
+ code0 = self._print(e)
461
+ lines.append(code0)
462
+ if i == len(expr.args) - 1:
463
+ lines.append("end")
464
+ return "\n".join(lines)
465
+
466
+ def _print_MatMul(self, expr):
467
+ c, m = expr.as_coeff_mmul()
468
+
469
+ sign = ""
470
+ if c.is_number:
471
+ re, im = c.as_real_imag()
472
+ if im.is_zero and re.is_negative:
473
+ expr = _keep_coeff(-c, m)
474
+ sign = "-"
475
+ elif re.is_zero and im.is_negative:
476
+ expr = _keep_coeff(-c, m)
477
+ sign = "-"
478
+
479
+ return sign + ' * '.join(
480
+ (self.parenthesize(arg, precedence(expr)) for arg in expr.args)
481
+ )
482
+
483
+
484
+ def indent_code(self, code):
485
+ """Accepts a string of code or a list of code lines"""
486
+
487
+ # code mostly copied from ccode
488
+ if isinstance(code, str):
489
+ code_lines = self.indent_code(code.splitlines(True))
490
+ return ''.join(code_lines)
491
+
492
+ tab = " "
493
+ inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
494
+ dec_regex = ('^end$', '^elseif ', '^else$')
495
+
496
+ # pre-strip left-space from the code
497
+ code = [ line.lstrip(' \t') for line in code ]
498
+
499
+ increase = [ int(any(search(re, line) for re in inc_regex))
500
+ for line in code ]
501
+ decrease = [ int(any(search(re, line) for re in dec_regex))
502
+ for line in code ]
503
+
504
+ pretty = []
505
+ level = 0
506
+ for n, line in enumerate(code):
507
+ if line in ('', '\n'):
508
+ pretty.append(line)
509
+ continue
510
+ level -= decrease[n]
511
+ pretty.append("%s%s" % (tab*level, line))
512
+ level += increase[n]
513
+ return pretty
514
+
515
+
516
+ def julia_code(expr, assign_to=None, **settings):
517
+ r"""Converts `expr` to a string of Julia code.
518
+
519
+ Parameters
520
+ ==========
521
+
522
+ expr : Expr
523
+ A SymPy expression to be converted.
524
+ assign_to : optional
525
+ When given, the argument is used as the name of the variable to which
526
+ the expression is assigned. Can be a string, ``Symbol``,
527
+ ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
528
+ expressions that generate multi-line statements.
529
+ precision : integer, optional
530
+ The precision for numbers such as pi [default=16].
531
+ user_functions : dict, optional
532
+ A dictionary where keys are ``FunctionClass`` instances and values are
533
+ their string representations. Alternatively, the dictionary value can
534
+ be a list of tuples i.e. [(argument_test, cfunction_string)]. See
535
+ below for examples.
536
+ human : bool, optional
537
+ If True, the result is a single string that may contain some constant
538
+ declarations for the number symbols. If False, the same information is
539
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
540
+ code_text). [default=True].
541
+ contract: bool, optional
542
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
543
+ rules and the corresponding nested loops over indices are generated.
544
+ Setting contract=False will not generate loops, instead the user is
545
+ responsible to provide values for the indices in the code.
546
+ [default=True].
547
+ inline: bool, optional
548
+ If True, we try to create single-statement code instead of multiple
549
+ statements. [default=True].
550
+
551
+ Examples
552
+ ========
553
+
554
+ >>> from sympy import julia_code, symbols, sin, pi
555
+ >>> x = symbols('x')
556
+ >>> julia_code(sin(x).series(x).removeO())
557
+ 'x .^ 5 / 120 - x .^ 3 / 6 + x'
558
+
559
+ >>> from sympy import Rational, ceiling
560
+ >>> x, y, tau = symbols("x, y, tau")
561
+ >>> julia_code((2*tau)**Rational(7, 2))
562
+ '8 * sqrt(2) * tau .^ (7 // 2)'
563
+
564
+ Note that element-wise (Hadamard) operations are used by default between
565
+ symbols. This is because its possible in Julia to write "vectorized"
566
+ code. It is harmless if the values are scalars.
567
+
568
+ >>> julia_code(sin(pi*x*y), assign_to="s")
569
+ 's = sin(pi * x .* y)'
570
+
571
+ If you need a matrix product "*" or matrix power "^", you can specify the
572
+ symbol as a ``MatrixSymbol``.
573
+
574
+ >>> from sympy import Symbol, MatrixSymbol
575
+ >>> n = Symbol('n', integer=True, positive=True)
576
+ >>> A = MatrixSymbol('A', n, n)
577
+ >>> julia_code(3*pi*A**3)
578
+ '(3 * pi) * A ^ 3'
579
+
580
+ This class uses several rules to decide which symbol to use a product.
581
+ Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
582
+ A HadamardProduct can be used to specify componentwise multiplication ".*"
583
+ of two MatrixSymbols. There is currently there is no easy way to specify
584
+ scalar symbols, so sometimes the code might have some minor cosmetic
585
+ issues. For example, suppose x and y are scalars and A is a Matrix, then
586
+ while a human programmer might write "(x^2*y)*A^3", we generate:
587
+
588
+ >>> julia_code(x**2*y*A**3)
589
+ '(x .^ 2 .* y) * A ^ 3'
590
+
591
+ Matrices are supported using Julia inline notation. When using
592
+ ``assign_to`` with matrices, the name can be specified either as a string
593
+ or as a ``MatrixSymbol``. The dimensions must align in the latter case.
594
+
595
+ >>> from sympy import Matrix, MatrixSymbol
596
+ >>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
597
+ >>> julia_code(mat, assign_to='A')
598
+ 'A = [x .^ 2 sin(x) ceil(x)]'
599
+
600
+ ``Piecewise`` expressions are implemented with logical masking by default.
601
+ Alternatively, you can pass "inline=False" to use if-else conditionals.
602
+ Note that if the ``Piecewise`` lacks a default term, represented by
603
+ ``(expr, True)`` then an error will be thrown. This is to prevent
604
+ generating an expression that may not evaluate to anything.
605
+
606
+ >>> from sympy import Piecewise
607
+ >>> pw = Piecewise((x + 1, x > 0), (x, True))
608
+ >>> julia_code(pw, assign_to=tau)
609
+ 'tau = ((x > 0) ? (x + 1) : (x))'
610
+
611
+ Note that any expression that can be generated normally can also exist
612
+ inside a Matrix:
613
+
614
+ >>> mat = Matrix([[x**2, pw, sin(x)]])
615
+ >>> julia_code(mat, assign_to='A')
616
+ 'A = [x .^ 2 ((x > 0) ? (x + 1) : (x)) sin(x)]'
617
+
618
+ Custom printing can be defined for certain types by passing a dictionary of
619
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
620
+ dictionary value can be a list of tuples i.e., [(argument_test,
621
+ cfunction_string)]. This can be used to call a custom Julia function.
622
+
623
+ >>> from sympy import Function
624
+ >>> f = Function('f')
625
+ >>> g = Function('g')
626
+ >>> custom_functions = {
627
+ ... "f": "existing_julia_fcn",
628
+ ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
629
+ ... (lambda x: not x.is_Matrix, "my_fcn")]
630
+ ... }
631
+ >>> mat = Matrix([[1, x]])
632
+ >>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
633
+ 'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
634
+
635
+ Support for loops is provided through ``Indexed`` types. With
636
+ ``contract=True`` these expressions will be turned into loops, whereas
637
+ ``contract=False`` will just print the assignment expression that should be
638
+ looped over:
639
+
640
+ >>> from sympy import Eq, IndexedBase, Idx
641
+ >>> len_y = 5
642
+ >>> y = IndexedBase('y', shape=(len_y,))
643
+ >>> t = IndexedBase('t', shape=(len_y,))
644
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
645
+ >>> i = Idx('i', len_y-1)
646
+ >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
647
+ >>> julia_code(e.rhs, assign_to=e.lhs, contract=False)
648
+ 'Dy[i] = (y[i + 1] - y[i]) ./ (t[i + 1] - t[i])'
649
+ """
650
+ return JuliaCodePrinter(settings).doprint(expr, assign_to)
651
+
652
+
653
+ def print_julia_code(expr, **settings):
654
+ """Prints the Julia representation of the given expression.
655
+
656
+ See `julia_code` for the meaning of the optional arguments.
657
+ """
658
+ print(julia_code(expr, **settings))
env-llmeval/lib/python3.10/site-packages/sympy/printing/lambdarepr.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .pycode import (
2
+ PythonCodePrinter,
3
+ MpmathPrinter,
4
+ )
5
+ from .numpy import NumPyPrinter # NumPyPrinter is imported for backward compatibility
6
+ from sympy.core.sorting import default_sort_key
7
+
8
+
9
+ __all__ = [
10
+ 'PythonCodePrinter',
11
+ 'MpmathPrinter', # MpmathPrinter is published for backward compatibility
12
+ 'NumPyPrinter',
13
+ 'LambdaPrinter',
14
+ 'NumPyPrinter',
15
+ 'IntervalPrinter',
16
+ 'lambdarepr',
17
+ ]
18
+
19
+
20
+ class LambdaPrinter(PythonCodePrinter):
21
+ """
22
+ This printer converts expressions into strings that can be used by
23
+ lambdify.
24
+ """
25
+ printmethod = "_lambdacode"
26
+
27
+
28
+ def _print_And(self, expr):
29
+ result = ['(']
30
+ for arg in sorted(expr.args, key=default_sort_key):
31
+ result.extend(['(', self._print(arg), ')'])
32
+ result.append(' and ')
33
+ result = result[:-1]
34
+ result.append(')')
35
+ return ''.join(result)
36
+
37
+ def _print_Or(self, expr):
38
+ result = ['(']
39
+ for arg in sorted(expr.args, key=default_sort_key):
40
+ result.extend(['(', self._print(arg), ')'])
41
+ result.append(' or ')
42
+ result = result[:-1]
43
+ result.append(')')
44
+ return ''.join(result)
45
+
46
+ def _print_Not(self, expr):
47
+ result = ['(', 'not (', self._print(expr.args[0]), '))']
48
+ return ''.join(result)
49
+
50
+ def _print_BooleanTrue(self, expr):
51
+ return "True"
52
+
53
+ def _print_BooleanFalse(self, expr):
54
+ return "False"
55
+
56
+ def _print_ITE(self, expr):
57
+ result = [
58
+ '((', self._print(expr.args[1]),
59
+ ') if (', self._print(expr.args[0]),
60
+ ') else (', self._print(expr.args[2]), '))'
61
+ ]
62
+ return ''.join(result)
63
+
64
+ def _print_NumberSymbol(self, expr):
65
+ return str(expr)
66
+
67
+ def _print_Pow(self, expr, **kwargs):
68
+ # XXX Temporary workaround. Should Python math printer be
69
+ # isolated from PythonCodePrinter?
70
+ return super(PythonCodePrinter, self)._print_Pow(expr, **kwargs)
71
+
72
+
73
+ # numexpr works by altering the string passed to numexpr.evaluate
74
+ # rather than by populating a namespace. Thus a special printer...
75
+ class NumExprPrinter(LambdaPrinter):
76
+ # key, value pairs correspond to SymPy name and numexpr name
77
+ # functions not appearing in this dict will raise a TypeError
78
+ printmethod = "_numexprcode"
79
+
80
+ _numexpr_functions = {
81
+ 'sin' : 'sin',
82
+ 'cos' : 'cos',
83
+ 'tan' : 'tan',
84
+ 'asin': 'arcsin',
85
+ 'acos': 'arccos',
86
+ 'atan': 'arctan',
87
+ 'atan2' : 'arctan2',
88
+ 'sinh' : 'sinh',
89
+ 'cosh' : 'cosh',
90
+ 'tanh' : 'tanh',
91
+ 'asinh': 'arcsinh',
92
+ 'acosh': 'arccosh',
93
+ 'atanh': 'arctanh',
94
+ 'ln' : 'log',
95
+ 'log': 'log',
96
+ 'exp': 'exp',
97
+ 'sqrt' : 'sqrt',
98
+ 'Abs' : 'abs',
99
+ 'conjugate' : 'conj',
100
+ 'im' : 'imag',
101
+ 're' : 'real',
102
+ 'where' : 'where',
103
+ 'complex' : 'complex',
104
+ 'contains' : 'contains',
105
+ }
106
+
107
+ module = 'numexpr'
108
+
109
+ def _print_ImaginaryUnit(self, expr):
110
+ return '1j'
111
+
112
+ def _print_seq(self, seq, delimiter=', '):
113
+ # simplified _print_seq taken from pretty.py
114
+ s = [self._print(item) for item in seq]
115
+ if s:
116
+ return delimiter.join(s)
117
+ else:
118
+ return ""
119
+
120
+ def _print_Function(self, e):
121
+ func_name = e.func.__name__
122
+
123
+ nstr = self._numexpr_functions.get(func_name, None)
124
+ if nstr is None:
125
+ # check for implemented_function
126
+ if hasattr(e, '_imp_'):
127
+ return "(%s)" % self._print(e._imp_(*e.args))
128
+ else:
129
+ raise TypeError("numexpr does not support function '%s'" %
130
+ func_name)
131
+ return "%s(%s)" % (nstr, self._print_seq(e.args))
132
+
133
+ def _print_Piecewise(self, expr):
134
+ "Piecewise function printer"
135
+ exprs = [self._print(arg.expr) for arg in expr.args]
136
+ conds = [self._print(arg.cond) for arg in expr.args]
137
+ # If [default_value, True] is a (expr, cond) sequence in a Piecewise object
138
+ # it will behave the same as passing the 'default' kwarg to select()
139
+ # *as long as* it is the last element in expr.args.
140
+ # If this is not the case, it may be triggered prematurely.
141
+ ans = []
142
+ parenthesis_count = 0
143
+ is_last_cond_True = False
144
+ for cond, expr in zip(conds, exprs):
145
+ if cond == 'True':
146
+ ans.append(expr)
147
+ is_last_cond_True = True
148
+ break
149
+ else:
150
+ ans.append('where(%s, %s, ' % (cond, expr))
151
+ parenthesis_count += 1
152
+ if not is_last_cond_True:
153
+ # See https://github.com/pydata/numexpr/issues/298
154
+ #
155
+ # simplest way to put a nan but raises
156
+ # 'RuntimeWarning: invalid value encountered in log'
157
+ #
158
+ # There are other ways to do this such as
159
+ #
160
+ # >>> import numexpr as ne
161
+ # >>> nan = float('nan')
162
+ # >>> ne.evaluate('where(x < 0, -1, nan)', {'x': [-1, 2, 3], 'nan':nan})
163
+ # array([-1., nan, nan])
164
+ #
165
+ # That needs to be handled in the lambdified function though rather
166
+ # than here in the printer.
167
+ ans.append('log(-1)')
168
+ return ''.join(ans) + ')' * parenthesis_count
169
+
170
+ def _print_ITE(self, expr):
171
+ from sympy.functions.elementary.piecewise import Piecewise
172
+ return self._print(expr.rewrite(Piecewise))
173
+
174
+ def blacklisted(self, expr):
175
+ raise TypeError("numexpr cannot be used with %s" %
176
+ expr.__class__.__name__)
177
+
178
+ # blacklist all Matrix printing
179
+ _print_SparseRepMatrix = \
180
+ _print_MutableSparseMatrix = \
181
+ _print_ImmutableSparseMatrix = \
182
+ _print_Matrix = \
183
+ _print_DenseMatrix = \
184
+ _print_MutableDenseMatrix = \
185
+ _print_ImmutableMatrix = \
186
+ _print_ImmutableDenseMatrix = \
187
+ blacklisted
188
+ # blacklist some Python expressions
189
+ _print_list = \
190
+ _print_tuple = \
191
+ _print_Tuple = \
192
+ _print_dict = \
193
+ _print_Dict = \
194
+ blacklisted
195
+
196
+ def _print_NumExprEvaluate(self, expr):
197
+ evaluate = self._module_format(self.module +".evaluate")
198
+ return "%s('%s', truediv=True)" % (evaluate, self._print(expr.expr))
199
+
200
+ def doprint(self, expr):
201
+ from sympy.codegen.ast import CodegenAST
202
+ from sympy.codegen.pynodes import NumExprEvaluate
203
+ if not isinstance(expr, CodegenAST):
204
+ expr = NumExprEvaluate(expr)
205
+ return super().doprint(expr)
206
+
207
+ def _print_Return(self, expr):
208
+ from sympy.codegen.pynodes import NumExprEvaluate
209
+ r, = expr.args
210
+ if not isinstance(r, NumExprEvaluate):
211
+ expr = expr.func(NumExprEvaluate(r))
212
+ return super()._print_Return(expr)
213
+
214
+ def _print_Assignment(self, expr):
215
+ from sympy.codegen.pynodes import NumExprEvaluate
216
+ lhs, rhs, *args = expr.args
217
+ if not isinstance(rhs, NumExprEvaluate):
218
+ expr = expr.func(lhs, NumExprEvaluate(rhs), *args)
219
+ return super()._print_Assignment(expr)
220
+
221
+ def _print_CodeBlock(self, expr):
222
+ from sympy.codegen.ast import CodegenAST
223
+ from sympy.codegen.pynodes import NumExprEvaluate
224
+ args = [ arg if isinstance(arg, CodegenAST) else NumExprEvaluate(arg) for arg in expr.args ]
225
+ return super()._print_CodeBlock(self, expr.func(*args))
226
+
227
+
228
+ class IntervalPrinter(MpmathPrinter, LambdaPrinter):
229
+ """Use ``lambda`` printer but print numbers as ``mpi`` intervals. """
230
+
231
+ def _print_Integer(self, expr):
232
+ return "mpi('%s')" % super(PythonCodePrinter, self)._print_Integer(expr)
233
+
234
+ def _print_Rational(self, expr):
235
+ return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr)
236
+
237
+ def _print_Half(self, expr):
238
+ return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr)
239
+
240
+ def _print_Pow(self, expr):
241
+ return super(MpmathPrinter, self)._print_Pow(expr, rational=True)
242
+
243
+
244
+ for k in NumExprPrinter._numexpr_functions:
245
+ setattr(NumExprPrinter, '_print_%s' % k, NumExprPrinter._print_Function)
246
+
247
+ def lambdarepr(expr, **settings):
248
+ """
249
+ Returns a string usable for lambdifying.
250
+ """
251
+ return LambdaPrinter(settings).doprint(expr)
env-llmeval/lib/python3.10/site-packages/sympy/printing/latex.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/printing/llvmjitcode.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Use llvmlite to create executable functions from SymPy expressions
3
+
4
+ This module requires llvmlite (https://github.com/numba/llvmlite).
5
+ '''
6
+
7
+ import ctypes
8
+
9
+ from sympy.external import import_module
10
+ from sympy.printing.printer import Printer
11
+ from sympy.core.singleton import S
12
+ from sympy.tensor.indexed import IndexedBase
13
+ from sympy.utilities.decorator import doctest_depends_on
14
+
15
+ llvmlite = import_module('llvmlite')
16
+ if llvmlite:
17
+ ll = import_module('llvmlite.ir').ir
18
+ llvm = import_module('llvmlite.binding').binding
19
+ llvm.initialize()
20
+ llvm.initialize_native_target()
21
+ llvm.initialize_native_asmprinter()
22
+
23
+
24
+ __doctest_requires__ = {('llvm_callable'): ['llvmlite']}
25
+
26
+
27
+ class LLVMJitPrinter(Printer):
28
+ '''Convert expressions to LLVM IR'''
29
+ def __init__(self, module, builder, fn, *args, **kwargs):
30
+ self.func_arg_map = kwargs.pop("func_arg_map", {})
31
+ if not llvmlite:
32
+ raise ImportError("llvmlite is required for LLVMJITPrinter")
33
+ super().__init__(*args, **kwargs)
34
+ self.fp_type = ll.DoubleType()
35
+ self.module = module
36
+ self.builder = builder
37
+ self.fn = fn
38
+ self.ext_fn = {} # keep track of wrappers to external functions
39
+ self.tmp_var = {}
40
+
41
+ def _add_tmp_var(self, name, value):
42
+ self.tmp_var[name] = value
43
+
44
+ def _print_Number(self, n):
45
+ return ll.Constant(self.fp_type, float(n))
46
+
47
+ def _print_Integer(self, expr):
48
+ return ll.Constant(self.fp_type, float(expr.p))
49
+
50
+ def _print_Symbol(self, s):
51
+ val = self.tmp_var.get(s)
52
+ if not val:
53
+ # look up parameter with name s
54
+ val = self.func_arg_map.get(s)
55
+ if not val:
56
+ raise LookupError("Symbol not found: %s" % s)
57
+ return val
58
+
59
+ def _print_Pow(self, expr):
60
+ base0 = self._print(expr.base)
61
+ if expr.exp == S.NegativeOne:
62
+ return self.builder.fdiv(ll.Constant(self.fp_type, 1.0), base0)
63
+ if expr.exp == S.Half:
64
+ fn = self.ext_fn.get("sqrt")
65
+ if not fn:
66
+ fn_type = ll.FunctionType(self.fp_type, [self.fp_type])
67
+ fn = ll.Function(self.module, fn_type, "sqrt")
68
+ self.ext_fn["sqrt"] = fn
69
+ return self.builder.call(fn, [base0], "sqrt")
70
+ if expr.exp == 2:
71
+ return self.builder.fmul(base0, base0)
72
+
73
+ exp0 = self._print(expr.exp)
74
+ fn = self.ext_fn.get("pow")
75
+ if not fn:
76
+ fn_type = ll.FunctionType(self.fp_type, [self.fp_type, self.fp_type])
77
+ fn = ll.Function(self.module, fn_type, "pow")
78
+ self.ext_fn["pow"] = fn
79
+ return self.builder.call(fn, [base0, exp0], "pow")
80
+
81
+ def _print_Mul(self, expr):
82
+ nodes = [self._print(a) for a in expr.args]
83
+ e = nodes[0]
84
+ for node in nodes[1:]:
85
+ e = self.builder.fmul(e, node)
86
+ return e
87
+
88
+ def _print_Add(self, expr):
89
+ nodes = [self._print(a) for a in expr.args]
90
+ e = nodes[0]
91
+ for node in nodes[1:]:
92
+ e = self.builder.fadd(e, node)
93
+ return e
94
+
95
+ # TODO - assumes all called functions take one double precision argument.
96
+ # Should have a list of math library functions to validate this.
97
+ def _print_Function(self, expr):
98
+ name = expr.func.__name__
99
+ e0 = self._print(expr.args[0])
100
+ fn = self.ext_fn.get(name)
101
+ if not fn:
102
+ fn_type = ll.FunctionType(self.fp_type, [self.fp_type])
103
+ fn = ll.Function(self.module, fn_type, name)
104
+ self.ext_fn[name] = fn
105
+ return self.builder.call(fn, [e0], name)
106
+
107
+ def emptyPrinter(self, expr):
108
+ raise TypeError("Unsupported type for LLVM JIT conversion: %s"
109
+ % type(expr))
110
+
111
+
112
+ # Used when parameters are passed by array. Often used in callbacks to
113
+ # handle a variable number of parameters.
114
+ class LLVMJitCallbackPrinter(LLVMJitPrinter):
115
+ def __init__(self, *args, **kwargs):
116
+ super().__init__(*args, **kwargs)
117
+
118
+ def _print_Indexed(self, expr):
119
+ array, idx = self.func_arg_map[expr.base]
120
+ offset = int(expr.indices[0].evalf())
121
+ array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), offset)])
122
+ fp_array_ptr = self.builder.bitcast(array_ptr, ll.PointerType(self.fp_type))
123
+ value = self.builder.load(fp_array_ptr)
124
+ return value
125
+
126
+ def _print_Symbol(self, s):
127
+ val = self.tmp_var.get(s)
128
+ if val:
129
+ return val
130
+
131
+ array, idx = self.func_arg_map.get(s, [None, 0])
132
+ if not array:
133
+ raise LookupError("Symbol not found: %s" % s)
134
+ array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), idx)])
135
+ fp_array_ptr = self.builder.bitcast(array_ptr,
136
+ ll.PointerType(self.fp_type))
137
+ value = self.builder.load(fp_array_ptr)
138
+ return value
139
+
140
+
141
+ # ensure lifetime of the execution engine persists (else call to compiled
142
+ # function will seg fault)
143
+ exe_engines = []
144
+
145
+ # ensure names for generated functions are unique
146
+ link_names = set()
147
+ current_link_suffix = 0
148
+
149
+
150
+ class LLVMJitCode:
151
+ def __init__(self, signature):
152
+ self.signature = signature
153
+ self.fp_type = ll.DoubleType()
154
+ self.module = ll.Module('mod1')
155
+ self.fn = None
156
+ self.llvm_arg_types = []
157
+ self.llvm_ret_type = self.fp_type
158
+ self.param_dict = {} # map symbol name to LLVM function argument
159
+ self.link_name = ''
160
+
161
+ def _from_ctype(self, ctype):
162
+ if ctype == ctypes.c_int:
163
+ return ll.IntType(32)
164
+ if ctype == ctypes.c_double:
165
+ return self.fp_type
166
+ if ctype == ctypes.POINTER(ctypes.c_double):
167
+ return ll.PointerType(self.fp_type)
168
+ if ctype == ctypes.c_void_p:
169
+ return ll.PointerType(ll.IntType(32))
170
+ if ctype == ctypes.py_object:
171
+ return ll.PointerType(ll.IntType(32))
172
+
173
+ print("Unhandled ctype = %s" % str(ctype))
174
+
175
+ def _create_args(self, func_args):
176
+ """Create types for function arguments"""
177
+ self.llvm_ret_type = self._from_ctype(self.signature.ret_type)
178
+ self.llvm_arg_types = \
179
+ [self._from_ctype(a) for a in self.signature.arg_ctypes]
180
+
181
+ def _create_function_base(self):
182
+ """Create function with name and type signature"""
183
+ global link_names, current_link_suffix
184
+ default_link_name = 'jit_func'
185
+ current_link_suffix += 1
186
+ self.link_name = default_link_name + str(current_link_suffix)
187
+ link_names.add(self.link_name)
188
+
189
+ fn_type = ll.FunctionType(self.llvm_ret_type, self.llvm_arg_types)
190
+ self.fn = ll.Function(self.module, fn_type, name=self.link_name)
191
+
192
+ def _create_param_dict(self, func_args):
193
+ """Mapping of symbolic values to function arguments"""
194
+ for i, a in enumerate(func_args):
195
+ self.fn.args[i].name = str(a)
196
+ self.param_dict[a] = self.fn.args[i]
197
+
198
+ def _create_function(self, expr):
199
+ """Create function body and return LLVM IR"""
200
+ bb_entry = self.fn.append_basic_block('entry')
201
+ builder = ll.IRBuilder(bb_entry)
202
+
203
+ lj = LLVMJitPrinter(self.module, builder, self.fn,
204
+ func_arg_map=self.param_dict)
205
+
206
+ ret = self._convert_expr(lj, expr)
207
+ lj.builder.ret(self._wrap_return(lj, ret))
208
+
209
+ strmod = str(self.module)
210
+ return strmod
211
+
212
+ def _wrap_return(self, lj, vals):
213
+ # Return a single double if there is one return value,
214
+ # else return a tuple of doubles.
215
+
216
+ # Don't wrap return value in this case
217
+ if self.signature.ret_type == ctypes.c_double:
218
+ return vals[0]
219
+
220
+ # Use this instead of a real PyObject*
221
+ void_ptr = ll.PointerType(ll.IntType(32))
222
+
223
+ # Create a wrapped double: PyObject* PyFloat_FromDouble(double v)
224
+ wrap_type = ll.FunctionType(void_ptr, [self.fp_type])
225
+ wrap_fn = ll.Function(lj.module, wrap_type, "PyFloat_FromDouble")
226
+
227
+ wrapped_vals = [lj.builder.call(wrap_fn, [v]) for v in vals]
228
+ if len(vals) == 1:
229
+ final_val = wrapped_vals[0]
230
+ else:
231
+ # Create a tuple: PyObject* PyTuple_Pack(Py_ssize_t n, ...)
232
+
233
+ # This should be Py_ssize_t
234
+ tuple_arg_types = [ll.IntType(32)]
235
+
236
+ tuple_arg_types.extend([void_ptr]*len(vals))
237
+ tuple_type = ll.FunctionType(void_ptr, tuple_arg_types)
238
+ tuple_fn = ll.Function(lj.module, tuple_type, "PyTuple_Pack")
239
+
240
+ tuple_args = [ll.Constant(ll.IntType(32), len(wrapped_vals))]
241
+ tuple_args.extend(wrapped_vals)
242
+
243
+ final_val = lj.builder.call(tuple_fn, tuple_args)
244
+
245
+ return final_val
246
+
247
+ def _convert_expr(self, lj, expr):
248
+ try:
249
+ # Match CSE return data structure.
250
+ if len(expr) == 2:
251
+ tmp_exprs = expr[0]
252
+ final_exprs = expr[1]
253
+ if len(final_exprs) != 1 and self.signature.ret_type == ctypes.c_double:
254
+ raise NotImplementedError("Return of multiple expressions not supported for this callback")
255
+ for name, e in tmp_exprs:
256
+ val = lj._print(e)
257
+ lj._add_tmp_var(name, val)
258
+ except TypeError:
259
+ final_exprs = [expr]
260
+
261
+ vals = [lj._print(e) for e in final_exprs]
262
+
263
+ return vals
264
+
265
+ def _compile_function(self, strmod):
266
+ global exe_engines
267
+ llmod = llvm.parse_assembly(strmod)
268
+
269
+ pmb = llvm.create_pass_manager_builder()
270
+ pmb.opt_level = 2
271
+ pass_manager = llvm.create_module_pass_manager()
272
+ pmb.populate(pass_manager)
273
+
274
+ pass_manager.run(llmod)
275
+
276
+ target_machine = \
277
+ llvm.Target.from_default_triple().create_target_machine()
278
+ exe_eng = llvm.create_mcjit_compiler(llmod, target_machine)
279
+ exe_eng.finalize_object()
280
+ exe_engines.append(exe_eng)
281
+
282
+ if False:
283
+ print("Assembly")
284
+ print(target_machine.emit_assembly(llmod))
285
+
286
+ fptr = exe_eng.get_function_address(self.link_name)
287
+
288
+ return fptr
289
+
290
+
291
+ class LLVMJitCodeCallback(LLVMJitCode):
292
+ def __init__(self, signature):
293
+ super().__init__(signature)
294
+
295
+ def _create_param_dict(self, func_args):
296
+ for i, a in enumerate(func_args):
297
+ if isinstance(a, IndexedBase):
298
+ self.param_dict[a] = (self.fn.args[i], i)
299
+ self.fn.args[i].name = str(a)
300
+ else:
301
+ self.param_dict[a] = (self.fn.args[self.signature.input_arg],
302
+ i)
303
+
304
+ def _create_function(self, expr):
305
+ """Create function body and return LLVM IR"""
306
+ bb_entry = self.fn.append_basic_block('entry')
307
+ builder = ll.IRBuilder(bb_entry)
308
+
309
+ lj = LLVMJitCallbackPrinter(self.module, builder, self.fn,
310
+ func_arg_map=self.param_dict)
311
+
312
+ ret = self._convert_expr(lj, expr)
313
+
314
+ if self.signature.ret_arg:
315
+ output_fp_ptr = builder.bitcast(self.fn.args[self.signature.ret_arg],
316
+ ll.PointerType(self.fp_type))
317
+ for i, val in enumerate(ret):
318
+ index = ll.Constant(ll.IntType(32), i)
319
+ output_array_ptr = builder.gep(output_fp_ptr, [index])
320
+ builder.store(val, output_array_ptr)
321
+ builder.ret(ll.Constant(ll.IntType(32), 0)) # return success
322
+ else:
323
+ lj.builder.ret(self._wrap_return(lj, ret))
324
+
325
+ strmod = str(self.module)
326
+ return strmod
327
+
328
+
329
+ class CodeSignature:
330
+ def __init__(self, ret_type):
331
+ self.ret_type = ret_type
332
+ self.arg_ctypes = []
333
+
334
+ # Input argument array element index
335
+ self.input_arg = 0
336
+
337
+ # For the case output value is referenced through a parameter rather
338
+ # than the return value
339
+ self.ret_arg = None
340
+
341
+
342
+ def _llvm_jit_code(args, expr, signature, callback_type):
343
+ """Create a native code function from a SymPy expression"""
344
+ if callback_type is None:
345
+ jit = LLVMJitCode(signature)
346
+ else:
347
+ jit = LLVMJitCodeCallback(signature)
348
+
349
+ jit._create_args(args)
350
+ jit._create_function_base()
351
+ jit._create_param_dict(args)
352
+ strmod = jit._create_function(expr)
353
+ if False:
354
+ print("LLVM IR")
355
+ print(strmod)
356
+ fptr = jit._compile_function(strmod)
357
+ return fptr
358
+
359
+
360
+ @doctest_depends_on(modules=('llvmlite', 'scipy'))
361
+ def llvm_callable(args, expr, callback_type=None):
362
+ '''Compile function from a SymPy expression
363
+
364
+ Expressions are evaluated using double precision arithmetic.
365
+ Some single argument math functions (exp, sin, cos, etc.) are supported
366
+ in expressions.
367
+
368
+ Parameters
369
+ ==========
370
+
371
+ args : List of Symbol
372
+ Arguments to the generated function. Usually the free symbols in
373
+ the expression. Currently each one is assumed to convert to
374
+ a double precision scalar.
375
+ expr : Expr, or (Replacements, Expr) as returned from 'cse'
376
+ Expression to compile.
377
+ callback_type : string
378
+ Create function with signature appropriate to use as a callback.
379
+ Currently supported:
380
+ 'scipy.integrate'
381
+ 'scipy.integrate.test'
382
+ 'cubature'
383
+
384
+ Returns
385
+ =======
386
+
387
+ Compiled function that can evaluate the expression.
388
+
389
+ Examples
390
+ ========
391
+
392
+ >>> import sympy.printing.llvmjitcode as jit
393
+ >>> from sympy.abc import a
394
+ >>> e = a*a + a + 1
395
+ >>> e1 = jit.llvm_callable([a], e)
396
+ >>> e.subs(a, 1.1) # Evaluate via substitution
397
+ 3.31000000000000
398
+ >>> e1(1.1) # Evaluate using JIT-compiled code
399
+ 3.3100000000000005
400
+
401
+
402
+ Callbacks for integration functions can be JIT compiled.
403
+ >>> import sympy.printing.llvmjitcode as jit
404
+ >>> from sympy.abc import a
405
+ >>> from sympy import integrate
406
+ >>> from scipy.integrate import quad
407
+ >>> e = a*a
408
+ >>> e1 = jit.llvm_callable([a], e, callback_type='scipy.integrate')
409
+ >>> integrate(e, (a, 0.0, 2.0))
410
+ 2.66666666666667
411
+ >>> quad(e1, 0.0, 2.0)[0]
412
+ 2.66666666666667
413
+
414
+ The 'cubature' callback is for the Python wrapper around the
415
+ cubature package ( https://github.com/saullocastro/cubature )
416
+ and ( http://ab-initio.mit.edu/wiki/index.php/Cubature )
417
+
418
+ There are two signatures for the SciPy integration callbacks.
419
+ The first ('scipy.integrate') is the function to be passed to the
420
+ integration routine, and will pass the signature checks.
421
+ The second ('scipy.integrate.test') is only useful for directly calling
422
+ the function using ctypes variables. It will not pass the signature checks
423
+ for scipy.integrate.
424
+
425
+ The return value from the cse module can also be compiled. This
426
+ can improve the performance of the compiled function. If multiple
427
+ expressions are given to cse, the compiled function returns a tuple.
428
+ The 'cubature' callback handles multiple expressions (set `fdim`
429
+ to match in the integration call.)
430
+ >>> import sympy.printing.llvmjitcode as jit
431
+ >>> from sympy import cse
432
+ >>> from sympy.abc import x,y
433
+ >>> e1 = x*x + y*y
434
+ >>> e2 = 4*(x*x + y*y) + 8.0
435
+ >>> after_cse = cse([e1,e2])
436
+ >>> after_cse
437
+ ([(x0, x**2), (x1, y**2)], [x0 + x1, 4*x0 + 4*x1 + 8.0])
438
+ >>> j1 = jit.llvm_callable([x,y], after_cse)
439
+ >>> j1(1.0, 2.0)
440
+ (5.0, 28.0)
441
+ '''
442
+
443
+ if not llvmlite:
444
+ raise ImportError("llvmlite is required for llvmjitcode")
445
+
446
+ signature = CodeSignature(ctypes.py_object)
447
+
448
+ arg_ctypes = []
449
+ if callback_type is None:
450
+ for _ in args:
451
+ arg_ctype = ctypes.c_double
452
+ arg_ctypes.append(arg_ctype)
453
+ elif callback_type in ('scipy.integrate', 'scipy.integrate.test'):
454
+ signature.ret_type = ctypes.c_double
455
+ arg_ctypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_double)]
456
+ arg_ctypes_formal = [ctypes.c_int, ctypes.c_double]
457
+ signature.input_arg = 1
458
+ elif callback_type == 'cubature':
459
+ arg_ctypes = [ctypes.c_int,
460
+ ctypes.POINTER(ctypes.c_double),
461
+ ctypes.c_void_p,
462
+ ctypes.c_int,
463
+ ctypes.POINTER(ctypes.c_double)
464
+ ]
465
+ signature.ret_type = ctypes.c_int
466
+ signature.input_arg = 1
467
+ signature.ret_arg = 4
468
+ else:
469
+ raise ValueError("Unknown callback type: %s" % callback_type)
470
+
471
+ signature.arg_ctypes = arg_ctypes
472
+
473
+ fptr = _llvm_jit_code(args, expr, signature, callback_type)
474
+
475
+ if callback_type and callback_type == 'scipy.integrate':
476
+ arg_ctypes = arg_ctypes_formal
477
+
478
+ # PYFUNCTYPE holds the GIL which is needed to prevent a segfault when
479
+ # calling PyFloat_FromDouble on Python 3.10. Probably it is better to use
480
+ # ctypes.c_double when returning a float rather than using ctypes.py_object
481
+ # and returning a PyFloat from inside the jitted function (i.e. let ctypes
482
+ # handle the conversion from double to PyFloat).
483
+ if signature.ret_type == ctypes.py_object:
484
+ FUNCTYPE = ctypes.PYFUNCTYPE
485
+ else:
486
+ FUNCTYPE = ctypes.CFUNCTYPE
487
+
488
+ cfunc = FUNCTYPE(signature.ret_type, *arg_ctypes)(fptr)
489
+ return cfunc
env-llmeval/lib/python3.10/site-packages/sympy/printing/maple.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Maple code printer
3
+
4
+ The MapleCodePrinter converts single SymPy expressions into single
5
+ Maple expressions, using the functions defined in the Maple objects where possible.
6
+
7
+
8
+ FIXME: This module is still under actively developed. Some functions may be not completed.
9
+ """
10
+
11
+ from sympy.core import S
12
+ from sympy.core.numbers import Integer, IntegerConstant, equal_valued
13
+ from sympy.printing.codeprinter import CodePrinter
14
+ from sympy.printing.precedence import precedence, PRECEDENCE
15
+
16
+ import sympy
17
+
18
+ _known_func_same_name = (
19
+ 'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinh', 'cosh', 'tanh', 'sech',
20
+ 'csch', 'coth', 'exp', 'floor', 'factorial', 'bernoulli', 'euler',
21
+ 'fibonacci', 'gcd', 'lcm', 'conjugate', 'Ci', 'Chi', 'Ei', 'Li', 'Si', 'Shi',
22
+ 'erf', 'erfc', 'harmonic', 'LambertW',
23
+ 'sqrt', # For automatic rewrites
24
+ )
25
+
26
+ known_functions = {
27
+ # SymPy -> Maple
28
+ 'Abs': 'abs',
29
+ 'log': 'ln',
30
+ 'asin': 'arcsin',
31
+ 'acos': 'arccos',
32
+ 'atan': 'arctan',
33
+ 'asec': 'arcsec',
34
+ 'acsc': 'arccsc',
35
+ 'acot': 'arccot',
36
+ 'asinh': 'arcsinh',
37
+ 'acosh': 'arccosh',
38
+ 'atanh': 'arctanh',
39
+ 'asech': 'arcsech',
40
+ 'acsch': 'arccsch',
41
+ 'acoth': 'arccoth',
42
+ 'ceiling': 'ceil',
43
+ 'Max' : 'max',
44
+ 'Min' : 'min',
45
+
46
+ 'factorial2': 'doublefactorial',
47
+ 'RisingFactorial': 'pochhammer',
48
+ 'besseli': 'BesselI',
49
+ 'besselj': 'BesselJ',
50
+ 'besselk': 'BesselK',
51
+ 'bessely': 'BesselY',
52
+ 'hankelh1': 'HankelH1',
53
+ 'hankelh2': 'HankelH2',
54
+ 'airyai': 'AiryAi',
55
+ 'airybi': 'AiryBi',
56
+ 'appellf1': 'AppellF1',
57
+ 'fresnelc': 'FresnelC',
58
+ 'fresnels': 'FresnelS',
59
+ 'lerchphi' : 'LerchPhi',
60
+ }
61
+
62
+ for _func in _known_func_same_name:
63
+ known_functions[_func] = _func
64
+
65
+ number_symbols = {
66
+ # SymPy -> Maple
67
+ S.Pi: 'Pi',
68
+ S.Exp1: 'exp(1)',
69
+ S.Catalan: 'Catalan',
70
+ S.EulerGamma: 'gamma',
71
+ S.GoldenRatio: '(1/2 + (1/2)*sqrt(5))'
72
+ }
73
+
74
+ spec_relational_ops = {
75
+ # SymPy -> Maple
76
+ '==': '=',
77
+ '!=': '<>'
78
+ }
79
+
80
+ not_supported_symbol = [
81
+ S.ComplexInfinity
82
+ ]
83
+
84
+ class MapleCodePrinter(CodePrinter):
85
+ """
86
+ Printer which converts a SymPy expression into a maple code.
87
+ """
88
+ printmethod = "_maple"
89
+ language = "maple"
90
+
91
+ _default_settings = {
92
+ 'order': None,
93
+ 'full_prec': 'auto',
94
+ 'human': True,
95
+ 'inline': True,
96
+ 'allow_unknown_functions': True,
97
+ }
98
+
99
+ def __init__(self, settings=None):
100
+ if settings is None:
101
+ settings = {}
102
+ super().__init__(settings)
103
+ self.known_functions = dict(known_functions)
104
+ userfuncs = settings.get('user_functions', {})
105
+ self.known_functions.update(userfuncs)
106
+
107
+ def _get_statement(self, codestring):
108
+ return "%s;" % codestring
109
+
110
+ def _get_comment(self, text):
111
+ return "# {}".format(text)
112
+
113
+ def _declare_number_const(self, name, value):
114
+ return "{} := {};".format(name,
115
+ value.evalf(self._settings['precision']))
116
+
117
+ def _format_code(self, lines):
118
+ return lines
119
+
120
+ def _print_tuple(self, expr):
121
+ return self._print(list(expr))
122
+
123
+ def _print_Tuple(self, expr):
124
+ return self._print(list(expr))
125
+
126
+ def _print_Assignment(self, expr):
127
+ lhs = self._print(expr.lhs)
128
+ rhs = self._print(expr.rhs)
129
+ return "{lhs} := {rhs}".format(lhs=lhs, rhs=rhs)
130
+
131
+ def _print_Pow(self, expr, **kwargs):
132
+ PREC = precedence(expr)
133
+ if equal_valued(expr.exp, -1):
134
+ return '1/%s' % (self.parenthesize(expr.base, PREC))
135
+ elif equal_valued(expr.exp, 0.5):
136
+ return 'sqrt(%s)' % self._print(expr.base)
137
+ elif equal_valued(expr.exp, -0.5):
138
+ return '1/sqrt(%s)' % self._print(expr.base)
139
+ else:
140
+ return '{base}^{exp}'.format(
141
+ base=self.parenthesize(expr.base, PREC),
142
+ exp=self.parenthesize(expr.exp, PREC))
143
+
144
+ def _print_Piecewise(self, expr):
145
+ if (expr.args[-1].cond is not True) and (expr.args[-1].cond != S.BooleanTrue):
146
+ # We need the last conditional to be a True, otherwise the resulting
147
+ # function may not return a result.
148
+ raise ValueError("All Piecewise expressions must contain an "
149
+ "(expr, True) statement to be used as a default "
150
+ "condition. Without one, the generated "
151
+ "expression may not evaluate to anything under "
152
+ "some condition.")
153
+ _coup_list = [
154
+ ("{c}, {e}".format(c=self._print(c),
155
+ e=self._print(e)) if c is not True and c is not S.BooleanTrue else "{e}".format(
156
+ e=self._print(e)))
157
+ for e, c in expr.args]
158
+ _inbrace = ', '.join(_coup_list)
159
+ return 'piecewise({_inbrace})'.format(_inbrace=_inbrace)
160
+
161
+ def _print_Rational(self, expr):
162
+ p, q = int(expr.p), int(expr.q)
163
+ return "{p}/{q}".format(p=str(p), q=str(q))
164
+
165
+ def _print_Relational(self, expr):
166
+ PREC=precedence(expr)
167
+ lhs_code = self.parenthesize(expr.lhs, PREC)
168
+ rhs_code = self.parenthesize(expr.rhs, PREC)
169
+ op = expr.rel_op
170
+ if op in spec_relational_ops:
171
+ op = spec_relational_ops[op]
172
+ return "{lhs} {rel_op} {rhs}".format(lhs=lhs_code, rel_op=op, rhs=rhs_code)
173
+
174
+ def _print_NumberSymbol(self, expr):
175
+ return number_symbols[expr]
176
+
177
+ def _print_NegativeInfinity(self, expr):
178
+ return '-infinity'
179
+
180
+ def _print_Infinity(self, expr):
181
+ return 'infinity'
182
+
183
+ def _print_Idx(self, expr):
184
+ return self._print(expr.label)
185
+
186
+ def _print_BooleanTrue(self, expr):
187
+ return "true"
188
+
189
+ def _print_BooleanFalse(self, expr):
190
+ return "false"
191
+
192
+ def _print_bool(self, expr):
193
+ return 'true' if expr else 'false'
194
+
195
+ def _print_NaN(self, expr):
196
+ return 'undefined'
197
+
198
+ def _get_matrix(self, expr, sparse=False):
199
+ if S.Zero in expr.shape:
200
+ _strM = 'Matrix([], storage = {storage})'.format(
201
+ storage='sparse' if sparse else 'rectangular')
202
+ else:
203
+ _strM = 'Matrix({list}, storage = {storage})'.format(
204
+ list=self._print(expr.tolist()),
205
+ storage='sparse' if sparse else 'rectangular')
206
+ return _strM
207
+
208
+ def _print_MatrixElement(self, expr):
209
+ return "{parent}[{i_maple}, {j_maple}]".format(
210
+ parent=self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True),
211
+ i_maple=self._print(expr.i + 1),
212
+ j_maple=self._print(expr.j + 1))
213
+
214
+ def _print_MatrixBase(self, expr):
215
+ return self._get_matrix(expr, sparse=False)
216
+
217
+ def _print_SparseRepMatrix(self, expr):
218
+ return self._get_matrix(expr, sparse=True)
219
+
220
+ def _print_Identity(self, expr):
221
+ if isinstance(expr.rows, (Integer, IntegerConstant)):
222
+ return self._print(sympy.SparseMatrix(expr))
223
+ else:
224
+ return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows))
225
+
226
+ def _print_MatMul(self, expr):
227
+ PREC=precedence(expr)
228
+ _fact_list = list(expr.args)
229
+ _const = None
230
+ if not isinstance(_fact_list[0], (sympy.MatrixBase, sympy.MatrixExpr,
231
+ sympy.MatrixSlice, sympy.MatrixSymbol)):
232
+ _const, _fact_list = _fact_list[0], _fact_list[1:]
233
+
234
+ if _const is None or _const == 1:
235
+ return '.'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
236
+ else:
237
+ return '{c}*{m}'.format(c=_const, m='.'.join(self.parenthesize(_m, PREC) for _m in _fact_list))
238
+
239
+ def _print_MatPow(self, expr):
240
+ # This function requires LinearAlgebra Function in Maple
241
+ return 'MatrixPower({A}, {n})'.format(A=self._print(expr.base), n=self._print(expr.exp))
242
+
243
+ def _print_HadamardProduct(self, expr):
244
+ PREC = precedence(expr)
245
+ _fact_list = list(expr.args)
246
+ return '*'.join(self.parenthesize(_m, PREC) for _m in _fact_list)
247
+
248
+ def _print_Derivative(self, expr):
249
+ _f, (_var, _order) = expr.args
250
+
251
+ if _order != 1:
252
+ _second_arg = '{var}${order}'.format(var=self._print(_var),
253
+ order=self._print(_order))
254
+ else:
255
+ _second_arg = '{var}'.format(var=self._print(_var))
256
+ return 'diff({func_expr}, {sec_arg})'.format(func_expr=self._print(_f), sec_arg=_second_arg)
257
+
258
+
259
+ def maple_code(expr, assign_to=None, **settings):
260
+ r"""Converts ``expr`` to a string of Maple code.
261
+
262
+ Parameters
263
+ ==========
264
+
265
+ expr : Expr
266
+ A SymPy expression to be converted.
267
+ assign_to : optional
268
+ When given, the argument is used as the name of the variable to which
269
+ the expression is assigned. Can be a string, ``Symbol``,
270
+ ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
271
+ expressions that generate multi-line statements.
272
+ precision : integer, optional
273
+ The precision for numbers such as pi [default=16].
274
+ user_functions : dict, optional
275
+ A dictionary where keys are ``FunctionClass`` instances and values are
276
+ their string representations. Alternatively, the dictionary value can
277
+ be a list of tuples i.e. [(argument_test, cfunction_string)]. See
278
+ below for examples.
279
+ human : bool, optional
280
+ If True, the result is a single string that may contain some constant
281
+ declarations for the number symbols. If False, the same information is
282
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
283
+ code_text). [default=True].
284
+ contract: bool, optional
285
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
286
+ rules and the corresponding nested loops over indices are generated.
287
+ Setting contract=False will not generate loops, instead the user is
288
+ responsible to provide values for the indices in the code.
289
+ [default=True].
290
+ inline: bool, optional
291
+ If True, we try to create single-statement code instead of multiple
292
+ statements. [default=True].
293
+
294
+ """
295
+ return MapleCodePrinter(settings).doprint(expr, assign_to)
296
+
297
+
298
+ def print_maple_code(expr, **settings):
299
+ """Prints the Maple representation of the given expression.
300
+
301
+ See :func:`maple_code` for the meaning of the optional arguments.
302
+
303
+ Examples
304
+ ========
305
+
306
+ >>> from sympy import print_maple_code, symbols
307
+ >>> x, y = symbols('x y')
308
+ >>> print_maple_code(x, assign_to=y)
309
+ y := x
310
+ """
311
+ print(maple_code(expr, **settings))
env-llmeval/lib/python3.10/site-packages/sympy/printing/mathematica.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mathematica code printer
3
+ """
4
+
5
+ from __future__ import annotations
6
+ from typing import Any
7
+
8
+ from sympy.core import Basic, Expr, Float
9
+ from sympy.core.sorting import default_sort_key
10
+
11
+ from sympy.printing.codeprinter import CodePrinter
12
+ from sympy.printing.precedence import precedence
13
+
14
+ # Used in MCodePrinter._print_Function(self)
15
+ known_functions = {
16
+ "exp": [(lambda x: True, "Exp")],
17
+ "log": [(lambda x: True, "Log")],
18
+ "sin": [(lambda x: True, "Sin")],
19
+ "cos": [(lambda x: True, "Cos")],
20
+ "tan": [(lambda x: True, "Tan")],
21
+ "cot": [(lambda x: True, "Cot")],
22
+ "sec": [(lambda x: True, "Sec")],
23
+ "csc": [(lambda x: True, "Csc")],
24
+ "asin": [(lambda x: True, "ArcSin")],
25
+ "acos": [(lambda x: True, "ArcCos")],
26
+ "atan": [(lambda x: True, "ArcTan")],
27
+ "acot": [(lambda x: True, "ArcCot")],
28
+ "asec": [(lambda x: True, "ArcSec")],
29
+ "acsc": [(lambda x: True, "ArcCsc")],
30
+ "atan2": [(lambda *x: True, "ArcTan")],
31
+ "sinh": [(lambda x: True, "Sinh")],
32
+ "cosh": [(lambda x: True, "Cosh")],
33
+ "tanh": [(lambda x: True, "Tanh")],
34
+ "coth": [(lambda x: True, "Coth")],
35
+ "sech": [(lambda x: True, "Sech")],
36
+ "csch": [(lambda x: True, "Csch")],
37
+ "asinh": [(lambda x: True, "ArcSinh")],
38
+ "acosh": [(lambda x: True, "ArcCosh")],
39
+ "atanh": [(lambda x: True, "ArcTanh")],
40
+ "acoth": [(lambda x: True, "ArcCoth")],
41
+ "asech": [(lambda x: True, "ArcSech")],
42
+ "acsch": [(lambda x: True, "ArcCsch")],
43
+ "sinc": [(lambda x: True, "Sinc")],
44
+ "conjugate": [(lambda x: True, "Conjugate")],
45
+ "Max": [(lambda *x: True, "Max")],
46
+ "Min": [(lambda *x: True, "Min")],
47
+ "erf": [(lambda x: True, "Erf")],
48
+ "erf2": [(lambda *x: True, "Erf")],
49
+ "erfc": [(lambda x: True, "Erfc")],
50
+ "erfi": [(lambda x: True, "Erfi")],
51
+ "erfinv": [(lambda x: True, "InverseErf")],
52
+ "erfcinv": [(lambda x: True, "InverseErfc")],
53
+ "erf2inv": [(lambda *x: True, "InverseErf")],
54
+ "expint": [(lambda *x: True, "ExpIntegralE")],
55
+ "Ei": [(lambda x: True, "ExpIntegralEi")],
56
+ "fresnelc": [(lambda x: True, "FresnelC")],
57
+ "fresnels": [(lambda x: True, "FresnelS")],
58
+ "gamma": [(lambda x: True, "Gamma")],
59
+ "uppergamma": [(lambda *x: True, "Gamma")],
60
+ "polygamma": [(lambda *x: True, "PolyGamma")],
61
+ "loggamma": [(lambda x: True, "LogGamma")],
62
+ "beta": [(lambda *x: True, "Beta")],
63
+ "Ci": [(lambda x: True, "CosIntegral")],
64
+ "Si": [(lambda x: True, "SinIntegral")],
65
+ "Chi": [(lambda x: True, "CoshIntegral")],
66
+ "Shi": [(lambda x: True, "SinhIntegral")],
67
+ "li": [(lambda x: True, "LogIntegral")],
68
+ "factorial": [(lambda x: True, "Factorial")],
69
+ "factorial2": [(lambda x: True, "Factorial2")],
70
+ "subfactorial": [(lambda x: True, "Subfactorial")],
71
+ "catalan": [(lambda x: True, "CatalanNumber")],
72
+ "harmonic": [(lambda *x: True, "HarmonicNumber")],
73
+ "lucas": [(lambda x: True, "LucasL")],
74
+ "RisingFactorial": [(lambda *x: True, "Pochhammer")],
75
+ "FallingFactorial": [(lambda *x: True, "FactorialPower")],
76
+ "laguerre": [(lambda *x: True, "LaguerreL")],
77
+ "assoc_laguerre": [(lambda *x: True, "LaguerreL")],
78
+ "hermite": [(lambda *x: True, "HermiteH")],
79
+ "jacobi": [(lambda *x: True, "JacobiP")],
80
+ "gegenbauer": [(lambda *x: True, "GegenbauerC")],
81
+ "chebyshevt": [(lambda *x: True, "ChebyshevT")],
82
+ "chebyshevu": [(lambda *x: True, "ChebyshevU")],
83
+ "legendre": [(lambda *x: True, "LegendreP")],
84
+ "assoc_legendre": [(lambda *x: True, "LegendreP")],
85
+ "mathieuc": [(lambda *x: True, "MathieuC")],
86
+ "mathieus": [(lambda *x: True, "MathieuS")],
87
+ "mathieucprime": [(lambda *x: True, "MathieuCPrime")],
88
+ "mathieusprime": [(lambda *x: True, "MathieuSPrime")],
89
+ "stieltjes": [(lambda x: True, "StieltjesGamma")],
90
+ "elliptic_e": [(lambda *x: True, "EllipticE")],
91
+ "elliptic_f": [(lambda *x: True, "EllipticE")],
92
+ "elliptic_k": [(lambda x: True, "EllipticK")],
93
+ "elliptic_pi": [(lambda *x: True, "EllipticPi")],
94
+ "zeta": [(lambda *x: True, "Zeta")],
95
+ "dirichlet_eta": [(lambda x: True, "DirichletEta")],
96
+ "riemann_xi": [(lambda x: True, "RiemannXi")],
97
+ "besseli": [(lambda *x: True, "BesselI")],
98
+ "besselj": [(lambda *x: True, "BesselJ")],
99
+ "besselk": [(lambda *x: True, "BesselK")],
100
+ "bessely": [(lambda *x: True, "BesselY")],
101
+ "hankel1": [(lambda *x: True, "HankelH1")],
102
+ "hankel2": [(lambda *x: True, "HankelH2")],
103
+ "airyai": [(lambda x: True, "AiryAi")],
104
+ "airybi": [(lambda x: True, "AiryBi")],
105
+ "airyaiprime": [(lambda x: True, "AiryAiPrime")],
106
+ "airybiprime": [(lambda x: True, "AiryBiPrime")],
107
+ "polylog": [(lambda *x: True, "PolyLog")],
108
+ "lerchphi": [(lambda *x: True, "LerchPhi")],
109
+ "gcd": [(lambda *x: True, "GCD")],
110
+ "lcm": [(lambda *x: True, "LCM")],
111
+ "jn": [(lambda *x: True, "SphericalBesselJ")],
112
+ "yn": [(lambda *x: True, "SphericalBesselY")],
113
+ "hyper": [(lambda *x: True, "HypergeometricPFQ")],
114
+ "meijerg": [(lambda *x: True, "MeijerG")],
115
+ "appellf1": [(lambda *x: True, "AppellF1")],
116
+ "DiracDelta": [(lambda x: True, "DiracDelta")],
117
+ "Heaviside": [(lambda x: True, "HeavisideTheta")],
118
+ "KroneckerDelta": [(lambda *x: True, "KroneckerDelta")],
119
+ "sqrt": [(lambda x: True, "Sqrt")], # For automatic rewrites
120
+ }
121
+
122
+
123
+ class MCodePrinter(CodePrinter):
124
+ """A printer to convert Python expressions to
125
+ strings of the Wolfram's Mathematica code
126
+ """
127
+ printmethod = "_mcode"
128
+ language = "Wolfram Language"
129
+
130
+ _default_settings: dict[str, Any] = {
131
+ 'order': None,
132
+ 'full_prec': 'auto',
133
+ 'precision': 15,
134
+ 'user_functions': {},
135
+ 'human': True,
136
+ 'allow_unknown_functions': False,
137
+ }
138
+
139
+ _number_symbols: set[tuple[Expr, Float]] = set()
140
+ _not_supported: set[Basic] = set()
141
+
142
+ def __init__(self, settings={}):
143
+ """Register function mappings supplied by user"""
144
+ CodePrinter.__init__(self, settings)
145
+ self.known_functions = dict(known_functions)
146
+ userfuncs = settings.get('user_functions', {}).copy()
147
+ for k, v in userfuncs.items():
148
+ if not isinstance(v, list):
149
+ userfuncs[k] = [(lambda *x: True, v)]
150
+ self.known_functions.update(userfuncs)
151
+
152
+ def _format_code(self, lines):
153
+ return lines
154
+
155
+ def _print_Pow(self, expr):
156
+ PREC = precedence(expr)
157
+ return '%s^%s' % (self.parenthesize(expr.base, PREC),
158
+ self.parenthesize(expr.exp, PREC))
159
+
160
+ def _print_Mul(self, expr):
161
+ PREC = precedence(expr)
162
+ c, nc = expr.args_cnc()
163
+ res = super()._print_Mul(expr.func(*c))
164
+ if nc:
165
+ res += '*'
166
+ res += '**'.join(self.parenthesize(a, PREC) for a in nc)
167
+ return res
168
+
169
+ def _print_Relational(self, expr):
170
+ lhs_code = self._print(expr.lhs)
171
+ rhs_code = self._print(expr.rhs)
172
+ op = expr.rel_op
173
+ return "{} {} {}".format(lhs_code, op, rhs_code)
174
+
175
+ # Primitive numbers
176
+ def _print_Zero(self, expr):
177
+ return '0'
178
+
179
+ def _print_One(self, expr):
180
+ return '1'
181
+
182
+ def _print_NegativeOne(self, expr):
183
+ return '-1'
184
+
185
+ def _print_Half(self, expr):
186
+ return '1/2'
187
+
188
+ def _print_ImaginaryUnit(self, expr):
189
+ return 'I'
190
+
191
+
192
+ # Infinity and invalid numbers
193
+ def _print_Infinity(self, expr):
194
+ return 'Infinity'
195
+
196
+ def _print_NegativeInfinity(self, expr):
197
+ return '-Infinity'
198
+
199
+ def _print_ComplexInfinity(self, expr):
200
+ return 'ComplexInfinity'
201
+
202
+ def _print_NaN(self, expr):
203
+ return 'Indeterminate'
204
+
205
+
206
+ # Mathematical constants
207
+ def _print_Exp1(self, expr):
208
+ return 'E'
209
+
210
+ def _print_Pi(self, expr):
211
+ return 'Pi'
212
+
213
+ def _print_GoldenRatio(self, expr):
214
+ return 'GoldenRatio'
215
+
216
+ def _print_TribonacciConstant(self, expr):
217
+ expanded = expr.expand(func=True)
218
+ PREC = precedence(expr)
219
+ return self.parenthesize(expanded, PREC)
220
+
221
+ def _print_EulerGamma(self, expr):
222
+ return 'EulerGamma'
223
+
224
+ def _print_Catalan(self, expr):
225
+ return 'Catalan'
226
+
227
+
228
+ def _print_list(self, expr):
229
+ return '{' + ', '.join(self.doprint(a) for a in expr) + '}'
230
+ _print_tuple = _print_list
231
+ _print_Tuple = _print_list
232
+
233
+ def _print_ImmutableDenseMatrix(self, expr):
234
+ return self.doprint(expr.tolist())
235
+
236
+ def _print_ImmutableSparseMatrix(self, expr):
237
+
238
+ def print_rule(pos, val):
239
+ return '{} -> {}'.format(
240
+ self.doprint((pos[0]+1, pos[1]+1)), self.doprint(val))
241
+
242
+ def print_data():
243
+ items = sorted(expr.todok().items(), key=default_sort_key)
244
+ return '{' + \
245
+ ', '.join(print_rule(k, v) for k, v in items) + \
246
+ '}'
247
+
248
+ def print_dims():
249
+ return self.doprint(expr.shape)
250
+
251
+ return 'SparseArray[{}, {}]'.format(print_data(), print_dims())
252
+
253
+ def _print_ImmutableDenseNDimArray(self, expr):
254
+ return self.doprint(expr.tolist())
255
+
256
+ def _print_ImmutableSparseNDimArray(self, expr):
257
+ def print_string_list(string_list):
258
+ return '{' + ', '.join(a for a in string_list) + '}'
259
+
260
+ def to_mathematica_index(*args):
261
+ """Helper function to change Python style indexing to
262
+ Pathematica indexing.
263
+
264
+ Python indexing (0, 1 ... n-1)
265
+ -> Mathematica indexing (1, 2 ... n)
266
+ """
267
+ return tuple(i + 1 for i in args)
268
+
269
+ def print_rule(pos, val):
270
+ """Helper function to print a rule of Mathematica"""
271
+ return '{} -> {}'.format(self.doprint(pos), self.doprint(val))
272
+
273
+ def print_data():
274
+ """Helper function to print data part of Mathematica
275
+ sparse array.
276
+
277
+ It uses the fourth notation ``SparseArray[data,{d1,d2,...}]``
278
+ from
279
+ https://reference.wolfram.com/language/ref/SparseArray.html
280
+
281
+ ``data`` must be formatted with rule.
282
+ """
283
+ return print_string_list(
284
+ [print_rule(
285
+ to_mathematica_index(*(expr._get_tuple_index(key))),
286
+ value)
287
+ for key, value in sorted(expr._sparse_array.items())]
288
+ )
289
+
290
+ def print_dims():
291
+ """Helper function to print dimensions part of Mathematica
292
+ sparse array.
293
+
294
+ It uses the fourth notation ``SparseArray[data,{d1,d2,...}]``
295
+ from
296
+ https://reference.wolfram.com/language/ref/SparseArray.html
297
+ """
298
+ return self.doprint(expr.shape)
299
+
300
+ return 'SparseArray[{}, {}]'.format(print_data(), print_dims())
301
+
302
+ def _print_Function(self, expr):
303
+ if expr.func.__name__ in self.known_functions:
304
+ cond_mfunc = self.known_functions[expr.func.__name__]
305
+ for cond, mfunc in cond_mfunc:
306
+ if cond(*expr.args):
307
+ return "%s[%s]" % (mfunc, self.stringify(expr.args, ", "))
308
+ elif expr.func.__name__ in self._rewriteable_functions:
309
+ # Simple rewrite to supported function possible
310
+ target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
311
+ if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
312
+ return self._print(expr.rewrite(target_f))
313
+ return expr.func.__name__ + "[%s]" % self.stringify(expr.args, ", ")
314
+
315
+ _print_MinMaxBase = _print_Function
316
+
317
+ def _print_LambertW(self, expr):
318
+ if len(expr.args) == 1:
319
+ return "ProductLog[{}]".format(self._print(expr.args[0]))
320
+ return "ProductLog[{}, {}]".format(
321
+ self._print(expr.args[1]), self._print(expr.args[0]))
322
+
323
+ def _print_Integral(self, expr):
324
+ if len(expr.variables) == 1 and not expr.limits[0][1:]:
325
+ args = [expr.args[0], expr.variables[0]]
326
+ else:
327
+ args = expr.args
328
+ return "Hold[Integrate[" + ', '.join(self.doprint(a) for a in args) + "]]"
329
+
330
+ def _print_Sum(self, expr):
331
+ return "Hold[Sum[" + ', '.join(self.doprint(a) for a in expr.args) + "]]"
332
+
333
+ def _print_Derivative(self, expr):
334
+ dexpr = expr.expr
335
+ dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]
336
+ return "Hold[D[" + ', '.join(self.doprint(a) for a in [dexpr] + dvars) + "]]"
337
+
338
+
339
+ def _get_comment(self, text):
340
+ return "(* {} *)".format(text)
341
+
342
+
343
+ def mathematica_code(expr, **settings):
344
+ r"""Converts an expr to a string of the Wolfram Mathematica code
345
+
346
+ Examples
347
+ ========
348
+
349
+ >>> from sympy import mathematica_code as mcode, symbols, sin
350
+ >>> x = symbols('x')
351
+ >>> mcode(sin(x).series(x).removeO())
352
+ '(1/120)*x^5 - 1/6*x^3 + x'
353
+ """
354
+ return MCodePrinter(settings).doprint(expr)
env-llmeval/lib/python3.10/site-packages/sympy/printing/mathml.py ADDED
@@ -0,0 +1,2126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A MathML printer.
3
+ """
4
+
5
+ from __future__ import annotations
6
+ from typing import Any
7
+
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.singleton import S
10
+ from sympy.core.sorting import default_sort_key
11
+ from sympy.core.sympify import sympify
12
+ from sympy.printing.conventions import split_super_sub, requires_partial
13
+ from sympy.printing.precedence import \
14
+ precedence_traditional, PRECEDENCE, PRECEDENCE_TRADITIONAL
15
+ from sympy.printing.pretty.pretty_symbology import greek_unicode
16
+ from sympy.printing.printer import Printer, print_function
17
+
18
+ from mpmath.libmp import prec_to_dps, repr_dps, to_str as mlib_to_str
19
+
20
+
21
+ class MathMLPrinterBase(Printer):
22
+ """Contains common code required for MathMLContentPrinter and
23
+ MathMLPresentationPrinter.
24
+ """
25
+
26
+ _default_settings: dict[str, Any] = {
27
+ "order": None,
28
+ "encoding": "utf-8",
29
+ "fold_frac_powers": False,
30
+ "fold_func_brackets": False,
31
+ "fold_short_frac": None,
32
+ "inv_trig_style": "abbreviated",
33
+ "ln_notation": False,
34
+ "long_frac_ratio": None,
35
+ "mat_delim": "[",
36
+ "mat_symbol_style": "plain",
37
+ "mul_symbol": None,
38
+ "root_notation": True,
39
+ "symbol_names": {},
40
+ "mul_symbol_mathml_numbers": '&#xB7;',
41
+ }
42
+
43
+ def __init__(self, settings=None):
44
+ Printer.__init__(self, settings)
45
+ from xml.dom.minidom import Document, Text
46
+
47
+ self.dom = Document()
48
+
49
+ # Workaround to allow strings to remain unescaped
50
+ # Based on
51
+ # https://stackoverflow.com/questions/38015864/python-xml-dom-minidom-\
52
+ # please-dont-escape-my-strings/38041194
53
+ class RawText(Text):
54
+ def writexml(self, writer, indent='', addindent='', newl=''):
55
+ if self.data:
56
+ writer.write('{}{}{}'.format(indent, self.data, newl))
57
+
58
+ def createRawTextNode(data):
59
+ r = RawText()
60
+ r.data = data
61
+ r.ownerDocument = self.dom
62
+ return r
63
+
64
+ self.dom.createTextNode = createRawTextNode
65
+
66
+ def doprint(self, expr):
67
+ """
68
+ Prints the expression as MathML.
69
+ """
70
+ mathML = Printer._print(self, expr)
71
+ unistr = mathML.toxml()
72
+ xmlbstr = unistr.encode('ascii', 'xmlcharrefreplace')
73
+ res = xmlbstr.decode()
74
+ return res
75
+
76
+ def apply_patch(self):
77
+ # Applying the patch of xml.dom.minidom bug
78
+ # Date: 2011-11-18
79
+ # Description: http://ronrothman.com/public/leftbraned/xml-dom-minidom\
80
+ # -toprettyxml-and-silly-whitespace/#best-solution
81
+ # Issue: https://bugs.python.org/issue4147
82
+ # Patch: https://hg.python.org/cpython/rev/7262f8f276ff/
83
+
84
+ from xml.dom.minidom import Element, Text, Node, _write_data
85
+
86
+ def writexml(self, writer, indent="", addindent="", newl=""):
87
+ # indent = current indentation
88
+ # addindent = indentation to add to higher levels
89
+ # newl = newline string
90
+ writer.write(indent + "<" + self.tagName)
91
+
92
+ attrs = self._get_attributes()
93
+ a_names = list(attrs.keys())
94
+ a_names.sort()
95
+
96
+ for a_name in a_names:
97
+ writer.write(" %s=\"" % a_name)
98
+ _write_data(writer, attrs[a_name].value)
99
+ writer.write("\"")
100
+ if self.childNodes:
101
+ writer.write(">")
102
+ if (len(self.childNodes) == 1 and
103
+ self.childNodes[0].nodeType == Node.TEXT_NODE):
104
+ self.childNodes[0].writexml(writer, '', '', '')
105
+ else:
106
+ writer.write(newl)
107
+ for node in self.childNodes:
108
+ node.writexml(
109
+ writer, indent + addindent, addindent, newl)
110
+ writer.write(indent)
111
+ writer.write("</%s>%s" % (self.tagName, newl))
112
+ else:
113
+ writer.write("/>%s" % (newl))
114
+ self._Element_writexml_old = Element.writexml
115
+ Element.writexml = writexml
116
+
117
+ def writexml(self, writer, indent="", addindent="", newl=""):
118
+ _write_data(writer, "%s%s%s" % (indent, self.data, newl))
119
+ self._Text_writexml_old = Text.writexml
120
+ Text.writexml = writexml
121
+
122
+ def restore_patch(self):
123
+ from xml.dom.minidom import Element, Text
124
+ Element.writexml = self._Element_writexml_old
125
+ Text.writexml = self._Text_writexml_old
126
+
127
+
128
+ class MathMLContentPrinter(MathMLPrinterBase):
129
+ """Prints an expression to the Content MathML markup language.
130
+
131
+ References: https://www.w3.org/TR/MathML2/chapter4.html
132
+ """
133
+ printmethod = "_mathml_content"
134
+
135
+ def mathml_tag(self, e):
136
+ """Returns the MathML tag for an expression."""
137
+ translate = {
138
+ 'Add': 'plus',
139
+ 'Mul': 'times',
140
+ 'Derivative': 'diff',
141
+ 'Number': 'cn',
142
+ 'int': 'cn',
143
+ 'Pow': 'power',
144
+ 'Max': 'max',
145
+ 'Min': 'min',
146
+ 'Abs': 'abs',
147
+ 'And': 'and',
148
+ 'Or': 'or',
149
+ 'Xor': 'xor',
150
+ 'Not': 'not',
151
+ 'Implies': 'implies',
152
+ 'Symbol': 'ci',
153
+ 'MatrixSymbol': 'ci',
154
+ 'RandomSymbol': 'ci',
155
+ 'Integral': 'int',
156
+ 'Sum': 'sum',
157
+ 'sin': 'sin',
158
+ 'cos': 'cos',
159
+ 'tan': 'tan',
160
+ 'cot': 'cot',
161
+ 'csc': 'csc',
162
+ 'sec': 'sec',
163
+ 'sinh': 'sinh',
164
+ 'cosh': 'cosh',
165
+ 'tanh': 'tanh',
166
+ 'coth': 'coth',
167
+ 'csch': 'csch',
168
+ 'sech': 'sech',
169
+ 'asin': 'arcsin',
170
+ 'asinh': 'arcsinh',
171
+ 'acos': 'arccos',
172
+ 'acosh': 'arccosh',
173
+ 'atan': 'arctan',
174
+ 'atanh': 'arctanh',
175
+ 'atan2': 'arctan',
176
+ 'acot': 'arccot',
177
+ 'acoth': 'arccoth',
178
+ 'asec': 'arcsec',
179
+ 'asech': 'arcsech',
180
+ 'acsc': 'arccsc',
181
+ 'acsch': 'arccsch',
182
+ 'log': 'ln',
183
+ 'Equality': 'eq',
184
+ 'Unequality': 'neq',
185
+ 'GreaterThan': 'geq',
186
+ 'LessThan': 'leq',
187
+ 'StrictGreaterThan': 'gt',
188
+ 'StrictLessThan': 'lt',
189
+ 'Union': 'union',
190
+ 'Intersection': 'intersect',
191
+ }
192
+
193
+ for cls in e.__class__.__mro__:
194
+ n = cls.__name__
195
+ if n in translate:
196
+ return translate[n]
197
+ # Not found in the MRO set
198
+ n = e.__class__.__name__
199
+ return n.lower()
200
+
201
+ def _print_Mul(self, expr):
202
+
203
+ if expr.could_extract_minus_sign():
204
+ x = self.dom.createElement('apply')
205
+ x.appendChild(self.dom.createElement('minus'))
206
+ x.appendChild(self._print_Mul(-expr))
207
+ return x
208
+
209
+ from sympy.simplify import fraction
210
+ numer, denom = fraction(expr)
211
+
212
+ if denom is not S.One:
213
+ x = self.dom.createElement('apply')
214
+ x.appendChild(self.dom.createElement('divide'))
215
+ x.appendChild(self._print(numer))
216
+ x.appendChild(self._print(denom))
217
+ return x
218
+
219
+ coeff, terms = expr.as_coeff_mul()
220
+ if coeff is S.One and len(terms) == 1:
221
+ # XXX since the negative coefficient has been handled, I don't
222
+ # think a coeff of 1 can remain
223
+ return self._print(terms[0])
224
+
225
+ if self.order != 'old':
226
+ terms = Mul._from_args(terms).as_ordered_factors()
227
+
228
+ x = self.dom.createElement('apply')
229
+ x.appendChild(self.dom.createElement('times'))
230
+ if coeff != 1:
231
+ x.appendChild(self._print(coeff))
232
+ for term in terms:
233
+ x.appendChild(self._print(term))
234
+ return x
235
+
236
+ def _print_Add(self, expr, order=None):
237
+ args = self._as_ordered_terms(expr, order=order)
238
+ lastProcessed = self._print(args[0])
239
+ plusNodes = []
240
+ for arg in args[1:]:
241
+ if arg.could_extract_minus_sign():
242
+ # use minus
243
+ x = self.dom.createElement('apply')
244
+ x.appendChild(self.dom.createElement('minus'))
245
+ x.appendChild(lastProcessed)
246
+ x.appendChild(self._print(-arg))
247
+ # invert expression since this is now minused
248
+ lastProcessed = x
249
+ if arg == args[-1]:
250
+ plusNodes.append(lastProcessed)
251
+ else:
252
+ plusNodes.append(lastProcessed)
253
+ lastProcessed = self._print(arg)
254
+ if arg == args[-1]:
255
+ plusNodes.append(self._print(arg))
256
+ if len(plusNodes) == 1:
257
+ return lastProcessed
258
+ x = self.dom.createElement('apply')
259
+ x.appendChild(self.dom.createElement('plus'))
260
+ while plusNodes:
261
+ x.appendChild(plusNodes.pop(0))
262
+ return x
263
+
264
+ def _print_Piecewise(self, expr):
265
+ if expr.args[-1].cond != True:
266
+ # We need the last conditional to be a True, otherwise the resulting
267
+ # function may not return a result.
268
+ raise ValueError("All Piecewise expressions must contain an "
269
+ "(expr, True) statement to be used as a default "
270
+ "condition. Without one, the generated "
271
+ "expression may not evaluate to anything under "
272
+ "some condition.")
273
+ root = self.dom.createElement('piecewise')
274
+ for i, (e, c) in enumerate(expr.args):
275
+ if i == len(expr.args) - 1 and c == True:
276
+ piece = self.dom.createElement('otherwise')
277
+ piece.appendChild(self._print(e))
278
+ else:
279
+ piece = self.dom.createElement('piece')
280
+ piece.appendChild(self._print(e))
281
+ piece.appendChild(self._print(c))
282
+ root.appendChild(piece)
283
+ return root
284
+
285
+ def _print_MatrixBase(self, m):
286
+ x = self.dom.createElement('matrix')
287
+ for i in range(m.rows):
288
+ x_r = self.dom.createElement('matrixrow')
289
+ for j in range(m.cols):
290
+ x_r.appendChild(self._print(m[i, j]))
291
+ x.appendChild(x_r)
292
+ return x
293
+
294
+ def _print_Rational(self, e):
295
+ if e.q == 1:
296
+ # don't divide
297
+ x = self.dom.createElement('cn')
298
+ x.appendChild(self.dom.createTextNode(str(e.p)))
299
+ return x
300
+ x = self.dom.createElement('apply')
301
+ x.appendChild(self.dom.createElement('divide'))
302
+ # numerator
303
+ xnum = self.dom.createElement('cn')
304
+ xnum.appendChild(self.dom.createTextNode(str(e.p)))
305
+ # denominator
306
+ xdenom = self.dom.createElement('cn')
307
+ xdenom.appendChild(self.dom.createTextNode(str(e.q)))
308
+ x.appendChild(xnum)
309
+ x.appendChild(xdenom)
310
+ return x
311
+
312
+ def _print_Limit(self, e):
313
+ x = self.dom.createElement('apply')
314
+ x.appendChild(self.dom.createElement(self.mathml_tag(e)))
315
+
316
+ x_1 = self.dom.createElement('bvar')
317
+ x_2 = self.dom.createElement('lowlimit')
318
+ x_1.appendChild(self._print(e.args[1]))
319
+ x_2.appendChild(self._print(e.args[2]))
320
+
321
+ x.appendChild(x_1)
322
+ x.appendChild(x_2)
323
+ x.appendChild(self._print(e.args[0]))
324
+ return x
325
+
326
+ def _print_ImaginaryUnit(self, e):
327
+ return self.dom.createElement('imaginaryi')
328
+
329
+ def _print_EulerGamma(self, e):
330
+ return self.dom.createElement('eulergamma')
331
+
332
+ def _print_GoldenRatio(self, e):
333
+ """We use unicode #x3c6 for Greek letter phi as defined here
334
+ https://www.w3.org/2003/entities/2007doc/isogrk1.html"""
335
+ x = self.dom.createElement('cn')
336
+ x.appendChild(self.dom.createTextNode("\N{GREEK SMALL LETTER PHI}"))
337
+ return x
338
+
339
+ def _print_Exp1(self, e):
340
+ return self.dom.createElement('exponentiale')
341
+
342
+ def _print_Pi(self, e):
343
+ return self.dom.createElement('pi')
344
+
345
+ def _print_Infinity(self, e):
346
+ return self.dom.createElement('infinity')
347
+
348
+ def _print_NaN(self, e):
349
+ return self.dom.createElement('notanumber')
350
+
351
+ def _print_EmptySet(self, e):
352
+ return self.dom.createElement('emptyset')
353
+
354
+ def _print_BooleanTrue(self, e):
355
+ return self.dom.createElement('true')
356
+
357
+ def _print_BooleanFalse(self, e):
358
+ return self.dom.createElement('false')
359
+
360
+ def _print_NegativeInfinity(self, e):
361
+ x = self.dom.createElement('apply')
362
+ x.appendChild(self.dom.createElement('minus'))
363
+ x.appendChild(self.dom.createElement('infinity'))
364
+ return x
365
+
366
+ def _print_Integral(self, e):
367
+ def lime_recur(limits):
368
+ x = self.dom.createElement('apply')
369
+ x.appendChild(self.dom.createElement(self.mathml_tag(e)))
370
+ bvar_elem = self.dom.createElement('bvar')
371
+ bvar_elem.appendChild(self._print(limits[0][0]))
372
+ x.appendChild(bvar_elem)
373
+
374
+ if len(limits[0]) == 3:
375
+ low_elem = self.dom.createElement('lowlimit')
376
+ low_elem.appendChild(self._print(limits[0][1]))
377
+ x.appendChild(low_elem)
378
+ up_elem = self.dom.createElement('uplimit')
379
+ up_elem.appendChild(self._print(limits[0][2]))
380
+ x.appendChild(up_elem)
381
+ if len(limits[0]) == 2:
382
+ up_elem = self.dom.createElement('uplimit')
383
+ up_elem.appendChild(self._print(limits[0][1]))
384
+ x.appendChild(up_elem)
385
+ if len(limits) == 1:
386
+ x.appendChild(self._print(e.function))
387
+ else:
388
+ x.appendChild(lime_recur(limits[1:]))
389
+ return x
390
+
391
+ limits = list(e.limits)
392
+ limits.reverse()
393
+ return lime_recur(limits)
394
+
395
+ def _print_Sum(self, e):
396
+ # Printer can be shared because Sum and Integral have the
397
+ # same internal representation.
398
+ return self._print_Integral(e)
399
+
400
+ def _print_Symbol(self, sym):
401
+ ci = self.dom.createElement(self.mathml_tag(sym))
402
+
403
+ def join(items):
404
+ if len(items) > 1:
405
+ mrow = self.dom.createElement('mml:mrow')
406
+ for i, item in enumerate(items):
407
+ if i > 0:
408
+ mo = self.dom.createElement('mml:mo')
409
+ mo.appendChild(self.dom.createTextNode(" "))
410
+ mrow.appendChild(mo)
411
+ mi = self.dom.createElement('mml:mi')
412
+ mi.appendChild(self.dom.createTextNode(item))
413
+ mrow.appendChild(mi)
414
+ return mrow
415
+ else:
416
+ mi = self.dom.createElement('mml:mi')
417
+ mi.appendChild(self.dom.createTextNode(items[0]))
418
+ return mi
419
+
420
+ # translate name, supers and subs to unicode characters
421
+ def translate(s):
422
+ if s in greek_unicode:
423
+ return greek_unicode.get(s)
424
+ else:
425
+ return s
426
+
427
+ name, supers, subs = split_super_sub(sym.name)
428
+ name = translate(name)
429
+ supers = [translate(sup) for sup in supers]
430
+ subs = [translate(sub) for sub in subs]
431
+
432
+ mname = self.dom.createElement('mml:mi')
433
+ mname.appendChild(self.dom.createTextNode(name))
434
+ if not supers:
435
+ if not subs:
436
+ ci.appendChild(self.dom.createTextNode(name))
437
+ else:
438
+ msub = self.dom.createElement('mml:msub')
439
+ msub.appendChild(mname)
440
+ msub.appendChild(join(subs))
441
+ ci.appendChild(msub)
442
+ else:
443
+ if not subs:
444
+ msup = self.dom.createElement('mml:msup')
445
+ msup.appendChild(mname)
446
+ msup.appendChild(join(supers))
447
+ ci.appendChild(msup)
448
+ else:
449
+ msubsup = self.dom.createElement('mml:msubsup')
450
+ msubsup.appendChild(mname)
451
+ msubsup.appendChild(join(subs))
452
+ msubsup.appendChild(join(supers))
453
+ ci.appendChild(msubsup)
454
+ return ci
455
+
456
+ _print_MatrixSymbol = _print_Symbol
457
+ _print_RandomSymbol = _print_Symbol
458
+
459
+ def _print_Pow(self, e):
460
+ # Here we use root instead of power if the exponent is the reciprocal
461
+ # of an integer
462
+ if (self._settings['root_notation'] and e.exp.is_Rational
463
+ and e.exp.p == 1):
464
+ x = self.dom.createElement('apply')
465
+ x.appendChild(self.dom.createElement('root'))
466
+ if e.exp.q != 2:
467
+ xmldeg = self.dom.createElement('degree')
468
+ xmlcn = self.dom.createElement('cn')
469
+ xmlcn.appendChild(self.dom.createTextNode(str(e.exp.q)))
470
+ xmldeg.appendChild(xmlcn)
471
+ x.appendChild(xmldeg)
472
+ x.appendChild(self._print(e.base))
473
+ return x
474
+
475
+ x = self.dom.createElement('apply')
476
+ x_1 = self.dom.createElement(self.mathml_tag(e))
477
+ x.appendChild(x_1)
478
+ x.appendChild(self._print(e.base))
479
+ x.appendChild(self._print(e.exp))
480
+ return x
481
+
482
+ def _print_Number(self, e):
483
+ x = self.dom.createElement(self.mathml_tag(e))
484
+ x.appendChild(self.dom.createTextNode(str(e)))
485
+ return x
486
+
487
+ def _print_Float(self, e):
488
+ x = self.dom.createElement(self.mathml_tag(e))
489
+ repr_e = mlib_to_str(e._mpf_, repr_dps(e._prec))
490
+ x.appendChild(self.dom.createTextNode(repr_e))
491
+ return x
492
+
493
+ def _print_Derivative(self, e):
494
+ x = self.dom.createElement('apply')
495
+ diff_symbol = self.mathml_tag(e)
496
+ if requires_partial(e.expr):
497
+ diff_symbol = 'partialdiff'
498
+ x.appendChild(self.dom.createElement(diff_symbol))
499
+ x_1 = self.dom.createElement('bvar')
500
+
501
+ for sym, times in reversed(e.variable_count):
502
+ x_1.appendChild(self._print(sym))
503
+ if times > 1:
504
+ degree = self.dom.createElement('degree')
505
+ degree.appendChild(self._print(sympify(times)))
506
+ x_1.appendChild(degree)
507
+
508
+ x.appendChild(x_1)
509
+ x.appendChild(self._print(e.expr))
510
+ return x
511
+
512
+ def _print_Function(self, e):
513
+ x = self.dom.createElement("apply")
514
+ x.appendChild(self.dom.createElement(self.mathml_tag(e)))
515
+ for arg in e.args:
516
+ x.appendChild(self._print(arg))
517
+ return x
518
+
519
+ def _print_Basic(self, e):
520
+ x = self.dom.createElement(self.mathml_tag(e))
521
+ for arg in e.args:
522
+ x.appendChild(self._print(arg))
523
+ return x
524
+
525
+ def _print_AssocOp(self, e):
526
+ x = self.dom.createElement('apply')
527
+ x_1 = self.dom.createElement(self.mathml_tag(e))
528
+ x.appendChild(x_1)
529
+ for arg in e.args:
530
+ x.appendChild(self._print(arg))
531
+ return x
532
+
533
+ def _print_Relational(self, e):
534
+ x = self.dom.createElement('apply')
535
+ x.appendChild(self.dom.createElement(self.mathml_tag(e)))
536
+ x.appendChild(self._print(e.lhs))
537
+ x.appendChild(self._print(e.rhs))
538
+ return x
539
+
540
+ def _print_list(self, seq):
541
+ """MathML reference for the <list> element:
542
+ https://www.w3.org/TR/MathML2/chapter4.html#contm.list"""
543
+ dom_element = self.dom.createElement('list')
544
+ for item in seq:
545
+ dom_element.appendChild(self._print(item))
546
+ return dom_element
547
+
548
+ def _print_int(self, p):
549
+ dom_element = self.dom.createElement(self.mathml_tag(p))
550
+ dom_element.appendChild(self.dom.createTextNode(str(p)))
551
+ return dom_element
552
+
553
+ _print_Implies = _print_AssocOp
554
+ _print_Not = _print_AssocOp
555
+ _print_Xor = _print_AssocOp
556
+
557
+ def _print_FiniteSet(self, e):
558
+ x = self.dom.createElement('set')
559
+ for arg in e.args:
560
+ x.appendChild(self._print(arg))
561
+ return x
562
+
563
+ def _print_Complement(self, e):
564
+ x = self.dom.createElement('apply')
565
+ x.appendChild(self.dom.createElement('setdiff'))
566
+ for arg in e.args:
567
+ x.appendChild(self._print(arg))
568
+ return x
569
+
570
+ def _print_ProductSet(self, e):
571
+ x = self.dom.createElement('apply')
572
+ x.appendChild(self.dom.createElement('cartesianproduct'))
573
+ for arg in e.args:
574
+ x.appendChild(self._print(arg))
575
+ return x
576
+
577
+ # XXX Symmetric difference is not supported for MathML content printers.
578
+
579
+
580
+ class MathMLPresentationPrinter(MathMLPrinterBase):
581
+ """Prints an expression to the Presentation MathML markup language.
582
+
583
+ References: https://www.w3.org/TR/MathML2/chapter3.html
584
+ """
585
+ printmethod = "_mathml_presentation"
586
+
587
+ def mathml_tag(self, e):
588
+ """Returns the MathML tag for an expression."""
589
+ translate = {
590
+ 'Number': 'mn',
591
+ 'Limit': '&#x2192;',
592
+ 'Derivative': '&dd;',
593
+ 'int': 'mn',
594
+ 'Symbol': 'mi',
595
+ 'Integral': '&int;',
596
+ 'Sum': '&#x2211;',
597
+ 'sin': 'sin',
598
+ 'cos': 'cos',
599
+ 'tan': 'tan',
600
+ 'cot': 'cot',
601
+ 'asin': 'arcsin',
602
+ 'asinh': 'arcsinh',
603
+ 'acos': 'arccos',
604
+ 'acosh': 'arccosh',
605
+ 'atan': 'arctan',
606
+ 'atanh': 'arctanh',
607
+ 'acot': 'arccot',
608
+ 'atan2': 'arctan',
609
+ 'Equality': '=',
610
+ 'Unequality': '&#x2260;',
611
+ 'GreaterThan': '&#x2265;',
612
+ 'LessThan': '&#x2264;',
613
+ 'StrictGreaterThan': '>',
614
+ 'StrictLessThan': '<',
615
+ 'lerchphi': '&#x3A6;',
616
+ 'zeta': '&#x3B6;',
617
+ 'dirichlet_eta': '&#x3B7;',
618
+ 'elliptic_k': '&#x39A;',
619
+ 'lowergamma': '&#x3B3;',
620
+ 'uppergamma': '&#x393;',
621
+ 'gamma': '&#x393;',
622
+ 'totient': '&#x3D5;',
623
+ 'reduced_totient': '&#x3BB;',
624
+ 'primenu': '&#x3BD;',
625
+ 'primeomega': '&#x3A9;',
626
+ 'fresnels': 'S',
627
+ 'fresnelc': 'C',
628
+ 'LambertW': 'W',
629
+ 'Heaviside': '&#x398;',
630
+ 'BooleanTrue': 'True',
631
+ 'BooleanFalse': 'False',
632
+ 'NoneType': 'None',
633
+ 'mathieus': 'S',
634
+ 'mathieuc': 'C',
635
+ 'mathieusprime': 'S&#x2032;',
636
+ 'mathieucprime': 'C&#x2032;',
637
+ }
638
+
639
+ def mul_symbol_selection():
640
+ if (self._settings["mul_symbol"] is None or
641
+ self._settings["mul_symbol"] == 'None'):
642
+ return '&InvisibleTimes;'
643
+ elif self._settings["mul_symbol"] == 'times':
644
+ return '&#xD7;'
645
+ elif self._settings["mul_symbol"] == 'dot':
646
+ return '&#xB7;'
647
+ elif self._settings["mul_symbol"] == 'ldot':
648
+ return '&#x2024;'
649
+ elif not isinstance(self._settings["mul_symbol"], str):
650
+ raise TypeError
651
+ else:
652
+ return self._settings["mul_symbol"]
653
+ for cls in e.__class__.__mro__:
654
+ n = cls.__name__
655
+ if n in translate:
656
+ return translate[n]
657
+ # Not found in the MRO set
658
+ if e.__class__.__name__ == "Mul":
659
+ return mul_symbol_selection()
660
+ n = e.__class__.__name__
661
+ return n.lower()
662
+
663
+ def parenthesize(self, item, level, strict=False):
664
+ prec_val = precedence_traditional(item)
665
+ if (prec_val < level) or ((not strict) and prec_val <= level):
666
+ brac = self.dom.createElement('mfenced')
667
+ brac.appendChild(self._print(item))
668
+ return brac
669
+ else:
670
+ return self._print(item)
671
+
672
+ def _print_Mul(self, expr):
673
+
674
+ def multiply(expr, mrow):
675
+ from sympy.simplify import fraction
676
+ numer, denom = fraction(expr)
677
+ if denom is not S.One:
678
+ frac = self.dom.createElement('mfrac')
679
+ if self._settings["fold_short_frac"] and len(str(expr)) < 7:
680
+ frac.setAttribute('bevelled', 'true')
681
+ xnum = self._print(numer)
682
+ xden = self._print(denom)
683
+ frac.appendChild(xnum)
684
+ frac.appendChild(xden)
685
+ mrow.appendChild(frac)
686
+ return mrow
687
+
688
+ coeff, terms = expr.as_coeff_mul()
689
+ if coeff is S.One and len(terms) == 1:
690
+ mrow.appendChild(self._print(terms[0]))
691
+ return mrow
692
+ if self.order != 'old':
693
+ terms = Mul._from_args(terms).as_ordered_factors()
694
+
695
+ if coeff != 1:
696
+ x = self._print(coeff)
697
+ y = self.dom.createElement('mo')
698
+ y.appendChild(self.dom.createTextNode(self.mathml_tag(expr)))
699
+ mrow.appendChild(x)
700
+ mrow.appendChild(y)
701
+ for term in terms:
702
+ mrow.appendChild(self.parenthesize(term, PRECEDENCE['Mul']))
703
+ if not term == terms[-1]:
704
+ y = self.dom.createElement('mo')
705
+ y.appendChild(self.dom.createTextNode(self.mathml_tag(expr)))
706
+ mrow.appendChild(y)
707
+ return mrow
708
+ mrow = self.dom.createElement('mrow')
709
+ if expr.could_extract_minus_sign():
710
+ x = self.dom.createElement('mo')
711
+ x.appendChild(self.dom.createTextNode('-'))
712
+ mrow.appendChild(x)
713
+ mrow = multiply(-expr, mrow)
714
+ else:
715
+ mrow = multiply(expr, mrow)
716
+
717
+ return mrow
718
+
719
+ def _print_Add(self, expr, order=None):
720
+ mrow = self.dom.createElement('mrow')
721
+ args = self._as_ordered_terms(expr, order=order)
722
+ mrow.appendChild(self._print(args[0]))
723
+ for arg in args[1:]:
724
+ if arg.could_extract_minus_sign():
725
+ # use minus
726
+ x = self.dom.createElement('mo')
727
+ x.appendChild(self.dom.createTextNode('-'))
728
+ y = self._print(-arg)
729
+ # invert expression since this is now minused
730
+ else:
731
+ x = self.dom.createElement('mo')
732
+ x.appendChild(self.dom.createTextNode('+'))
733
+ y = self._print(arg)
734
+ mrow.appendChild(x)
735
+ mrow.appendChild(y)
736
+
737
+ return mrow
738
+
739
+ def _print_MatrixBase(self, m):
740
+ table = self.dom.createElement('mtable')
741
+ for i in range(m.rows):
742
+ x = self.dom.createElement('mtr')
743
+ for j in range(m.cols):
744
+ y = self.dom.createElement('mtd')
745
+ y.appendChild(self._print(m[i, j]))
746
+ x.appendChild(y)
747
+ table.appendChild(x)
748
+ if self._settings["mat_delim"] == '':
749
+ return table
750
+ brac = self.dom.createElement('mfenced')
751
+ if self._settings["mat_delim"] == "[":
752
+ brac.setAttribute('close', ']')
753
+ brac.setAttribute('open', '[')
754
+ brac.appendChild(table)
755
+ return brac
756
+
757
+ def _get_printed_Rational(self, e, folded=None):
758
+ if e.p < 0:
759
+ p = -e.p
760
+ else:
761
+ p = e.p
762
+ x = self.dom.createElement('mfrac')
763
+ if folded or self._settings["fold_short_frac"]:
764
+ x.setAttribute('bevelled', 'true')
765
+ x.appendChild(self._print(p))
766
+ x.appendChild(self._print(e.q))
767
+ if e.p < 0:
768
+ mrow = self.dom.createElement('mrow')
769
+ mo = self.dom.createElement('mo')
770
+ mo.appendChild(self.dom.createTextNode('-'))
771
+ mrow.appendChild(mo)
772
+ mrow.appendChild(x)
773
+ return mrow
774
+ else:
775
+ return x
776
+
777
+ def _print_Rational(self, e):
778
+ if e.q == 1:
779
+ # don't divide
780
+ return self._print(e.p)
781
+
782
+ return self._get_printed_Rational(e, self._settings["fold_short_frac"])
783
+
784
+ def _print_Limit(self, e):
785
+ mrow = self.dom.createElement('mrow')
786
+ munder = self.dom.createElement('munder')
787
+ mi = self.dom.createElement('mi')
788
+ mi.appendChild(self.dom.createTextNode('lim'))
789
+
790
+ x = self.dom.createElement('mrow')
791
+ x_1 = self._print(e.args[1])
792
+ arrow = self.dom.createElement('mo')
793
+ arrow.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
794
+ x_2 = self._print(e.args[2])
795
+ x.appendChild(x_1)
796
+ x.appendChild(arrow)
797
+ x.appendChild(x_2)
798
+
799
+ munder.appendChild(mi)
800
+ munder.appendChild(x)
801
+ mrow.appendChild(munder)
802
+ mrow.appendChild(self._print(e.args[0]))
803
+
804
+ return mrow
805
+
806
+ def _print_ImaginaryUnit(self, e):
807
+ x = self.dom.createElement('mi')
808
+ x.appendChild(self.dom.createTextNode('&ImaginaryI;'))
809
+ return x
810
+
811
+ def _print_GoldenRatio(self, e):
812
+ x = self.dom.createElement('mi')
813
+ x.appendChild(self.dom.createTextNode('&#x3A6;'))
814
+ return x
815
+
816
+ def _print_Exp1(self, e):
817
+ x = self.dom.createElement('mi')
818
+ x.appendChild(self.dom.createTextNode('&ExponentialE;'))
819
+ return x
820
+
821
+ def _print_Pi(self, e):
822
+ x = self.dom.createElement('mi')
823
+ x.appendChild(self.dom.createTextNode('&pi;'))
824
+ return x
825
+
826
+ def _print_Infinity(self, e):
827
+ x = self.dom.createElement('mi')
828
+ x.appendChild(self.dom.createTextNode('&#x221E;'))
829
+ return x
830
+
831
+ def _print_NegativeInfinity(self, e):
832
+ mrow = self.dom.createElement('mrow')
833
+ y = self.dom.createElement('mo')
834
+ y.appendChild(self.dom.createTextNode('-'))
835
+ x = self._print_Infinity(e)
836
+ mrow.appendChild(y)
837
+ mrow.appendChild(x)
838
+ return mrow
839
+
840
+ def _print_HBar(self, e):
841
+ x = self.dom.createElement('mi')
842
+ x.appendChild(self.dom.createTextNode('&#x210F;'))
843
+ return x
844
+
845
+ def _print_EulerGamma(self, e):
846
+ x = self.dom.createElement('mi')
847
+ x.appendChild(self.dom.createTextNode('&#x3B3;'))
848
+ return x
849
+
850
+ def _print_TribonacciConstant(self, e):
851
+ x = self.dom.createElement('mi')
852
+ x.appendChild(self.dom.createTextNode('TribonacciConstant'))
853
+ return x
854
+
855
+ def _print_Dagger(self, e):
856
+ msup = self.dom.createElement('msup')
857
+ msup.appendChild(self._print(e.args[0]))
858
+ msup.appendChild(self.dom.createTextNode('&#x2020;'))
859
+ return msup
860
+
861
+ def _print_Contains(self, e):
862
+ mrow = self.dom.createElement('mrow')
863
+ mrow.appendChild(self._print(e.args[0]))
864
+ mo = self.dom.createElement('mo')
865
+ mo.appendChild(self.dom.createTextNode('&#x2208;'))
866
+ mrow.appendChild(mo)
867
+ mrow.appendChild(self._print(e.args[1]))
868
+ return mrow
869
+
870
+ def _print_HilbertSpace(self, e):
871
+ x = self.dom.createElement('mi')
872
+ x.appendChild(self.dom.createTextNode('&#x210B;'))
873
+ return x
874
+
875
+ def _print_ComplexSpace(self, e):
876
+ msup = self.dom.createElement('msup')
877
+ msup.appendChild(self.dom.createTextNode('&#x1D49E;'))
878
+ msup.appendChild(self._print(e.args[0]))
879
+ return msup
880
+
881
+ def _print_FockSpace(self, e):
882
+ x = self.dom.createElement('mi')
883
+ x.appendChild(self.dom.createTextNode('&#x2131;'))
884
+ return x
885
+
886
+
887
+ def _print_Integral(self, expr):
888
+ intsymbols = {1: "&#x222B;", 2: "&#x222C;", 3: "&#x222D;"}
889
+
890
+ mrow = self.dom.createElement('mrow')
891
+ if len(expr.limits) <= 3 and all(len(lim) == 1 for lim in expr.limits):
892
+ # Only up to three-integral signs exists
893
+ mo = self.dom.createElement('mo')
894
+ mo.appendChild(self.dom.createTextNode(intsymbols[len(expr.limits)]))
895
+ mrow.appendChild(mo)
896
+ else:
897
+ # Either more than three or limits provided
898
+ for lim in reversed(expr.limits):
899
+ mo = self.dom.createElement('mo')
900
+ mo.appendChild(self.dom.createTextNode(intsymbols[1]))
901
+ if len(lim) == 1:
902
+ mrow.appendChild(mo)
903
+ if len(lim) == 2:
904
+ msup = self.dom.createElement('msup')
905
+ msup.appendChild(mo)
906
+ msup.appendChild(self._print(lim[1]))
907
+ mrow.appendChild(msup)
908
+ if len(lim) == 3:
909
+ msubsup = self.dom.createElement('msubsup')
910
+ msubsup.appendChild(mo)
911
+ msubsup.appendChild(self._print(lim[1]))
912
+ msubsup.appendChild(self._print(lim[2]))
913
+ mrow.appendChild(msubsup)
914
+ # print function
915
+ mrow.appendChild(self.parenthesize(expr.function, PRECEDENCE["Mul"],
916
+ strict=True))
917
+ # print integration variables
918
+ for lim in reversed(expr.limits):
919
+ d = self.dom.createElement('mo')
920
+ d.appendChild(self.dom.createTextNode('&dd;'))
921
+ mrow.appendChild(d)
922
+ mrow.appendChild(self._print(lim[0]))
923
+ return mrow
924
+
925
+ def _print_Sum(self, e):
926
+ limits = list(e.limits)
927
+ subsup = self.dom.createElement('munderover')
928
+ low_elem = self._print(limits[0][1])
929
+ up_elem = self._print(limits[0][2])
930
+ summand = self.dom.createElement('mo')
931
+ summand.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
932
+
933
+ low = self.dom.createElement('mrow')
934
+ var = self._print(limits[0][0])
935
+ equal = self.dom.createElement('mo')
936
+ equal.appendChild(self.dom.createTextNode('='))
937
+ low.appendChild(var)
938
+ low.appendChild(equal)
939
+ low.appendChild(low_elem)
940
+
941
+ subsup.appendChild(summand)
942
+ subsup.appendChild(low)
943
+ subsup.appendChild(up_elem)
944
+
945
+ mrow = self.dom.createElement('mrow')
946
+ mrow.appendChild(subsup)
947
+ if len(str(e.function)) == 1:
948
+ mrow.appendChild(self._print(e.function))
949
+ else:
950
+ fence = self.dom.createElement('mfenced')
951
+ fence.appendChild(self._print(e.function))
952
+ mrow.appendChild(fence)
953
+
954
+ return mrow
955
+
956
+ def _print_Symbol(self, sym, style='plain'):
957
+ def join(items):
958
+ if len(items) > 1:
959
+ mrow = self.dom.createElement('mrow')
960
+ for i, item in enumerate(items):
961
+ if i > 0:
962
+ mo = self.dom.createElement('mo')
963
+ mo.appendChild(self.dom.createTextNode(" "))
964
+ mrow.appendChild(mo)
965
+ mi = self.dom.createElement('mi')
966
+ mi.appendChild(self.dom.createTextNode(item))
967
+ mrow.appendChild(mi)
968
+ return mrow
969
+ else:
970
+ mi = self.dom.createElement('mi')
971
+ mi.appendChild(self.dom.createTextNode(items[0]))
972
+ return mi
973
+
974
+ # translate name, supers and subs to unicode characters
975
+ def translate(s):
976
+ if s in greek_unicode:
977
+ return greek_unicode.get(s)
978
+ else:
979
+ return s
980
+
981
+ name, supers, subs = split_super_sub(sym.name)
982
+ name = translate(name)
983
+ supers = [translate(sup) for sup in supers]
984
+ subs = [translate(sub) for sub in subs]
985
+
986
+ mname = self.dom.createElement('mi')
987
+ mname.appendChild(self.dom.createTextNode(name))
988
+ if len(supers) == 0:
989
+ if len(subs) == 0:
990
+ x = mname
991
+ else:
992
+ x = self.dom.createElement('msub')
993
+ x.appendChild(mname)
994
+ x.appendChild(join(subs))
995
+ else:
996
+ if len(subs) == 0:
997
+ x = self.dom.createElement('msup')
998
+ x.appendChild(mname)
999
+ x.appendChild(join(supers))
1000
+ else:
1001
+ x = self.dom.createElement('msubsup')
1002
+ x.appendChild(mname)
1003
+ x.appendChild(join(subs))
1004
+ x.appendChild(join(supers))
1005
+ # Set bold font?
1006
+ if style == 'bold':
1007
+ x.setAttribute('mathvariant', 'bold')
1008
+ return x
1009
+
1010
+ def _print_MatrixSymbol(self, sym):
1011
+ return self._print_Symbol(sym,
1012
+ style=self._settings['mat_symbol_style'])
1013
+
1014
+ _print_RandomSymbol = _print_Symbol
1015
+
1016
+ def _print_conjugate(self, expr):
1017
+ enc = self.dom.createElement('menclose')
1018
+ enc.setAttribute('notation', 'top')
1019
+ enc.appendChild(self._print(expr.args[0]))
1020
+ return enc
1021
+
1022
+ def _print_operator_after(self, op, expr):
1023
+ row = self.dom.createElement('mrow')
1024
+ row.appendChild(self.parenthesize(expr, PRECEDENCE["Func"]))
1025
+ mo = self.dom.createElement('mo')
1026
+ mo.appendChild(self.dom.createTextNode(op))
1027
+ row.appendChild(mo)
1028
+ return row
1029
+
1030
+ def _print_factorial(self, expr):
1031
+ return self._print_operator_after('!', expr.args[0])
1032
+
1033
+ def _print_factorial2(self, expr):
1034
+ return self._print_operator_after('!!', expr.args[0])
1035
+
1036
+ def _print_binomial(self, expr):
1037
+ brac = self.dom.createElement('mfenced')
1038
+ frac = self.dom.createElement('mfrac')
1039
+ frac.setAttribute('linethickness', '0')
1040
+ frac.appendChild(self._print(expr.args[0]))
1041
+ frac.appendChild(self._print(expr.args[1]))
1042
+ brac.appendChild(frac)
1043
+ return brac
1044
+
1045
+ def _print_Pow(self, e):
1046
+ # Here we use root instead of power if the exponent is the
1047
+ # reciprocal of an integer
1048
+ if (e.exp.is_Rational and abs(e.exp.p) == 1 and e.exp.q != 1 and
1049
+ self._settings['root_notation']):
1050
+ if e.exp.q == 2:
1051
+ x = self.dom.createElement('msqrt')
1052
+ x.appendChild(self._print(e.base))
1053
+ if e.exp.q != 2:
1054
+ x = self.dom.createElement('mroot')
1055
+ x.appendChild(self._print(e.base))
1056
+ x.appendChild(self._print(e.exp.q))
1057
+ if e.exp.p == -1:
1058
+ frac = self.dom.createElement('mfrac')
1059
+ frac.appendChild(self._print(1))
1060
+ frac.appendChild(x)
1061
+ return frac
1062
+ else:
1063
+ return x
1064
+
1065
+ if e.exp.is_Rational and e.exp.q != 1:
1066
+ if e.exp.is_negative:
1067
+ top = self.dom.createElement('mfrac')
1068
+ top.appendChild(self._print(1))
1069
+ x = self.dom.createElement('msup')
1070
+ x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
1071
+ x.appendChild(self._get_printed_Rational(-e.exp,
1072
+ self._settings['fold_frac_powers']))
1073
+ top.appendChild(x)
1074
+ return top
1075
+ else:
1076
+ x = self.dom.createElement('msup')
1077
+ x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
1078
+ x.appendChild(self._get_printed_Rational(e.exp,
1079
+ self._settings['fold_frac_powers']))
1080
+ return x
1081
+
1082
+ if e.exp.is_negative:
1083
+ top = self.dom.createElement('mfrac')
1084
+ top.appendChild(self._print(1))
1085
+ if e.exp == -1:
1086
+ top.appendChild(self._print(e.base))
1087
+ else:
1088
+ x = self.dom.createElement('msup')
1089
+ x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
1090
+ x.appendChild(self._print(-e.exp))
1091
+ top.appendChild(x)
1092
+ return top
1093
+
1094
+ x = self.dom.createElement('msup')
1095
+ x.appendChild(self.parenthesize(e.base, PRECEDENCE['Pow']))
1096
+ x.appendChild(self._print(e.exp))
1097
+ return x
1098
+
1099
+ def _print_Number(self, e):
1100
+ x = self.dom.createElement(self.mathml_tag(e))
1101
+ x.appendChild(self.dom.createTextNode(str(e)))
1102
+ return x
1103
+
1104
+ def _print_AccumulationBounds(self, i):
1105
+ brac = self.dom.createElement('mfenced')
1106
+ brac.setAttribute('close', '\u27e9')
1107
+ brac.setAttribute('open', '\u27e8')
1108
+ brac.appendChild(self._print(i.min))
1109
+ brac.appendChild(self._print(i.max))
1110
+ return brac
1111
+
1112
+ def _print_Derivative(self, e):
1113
+
1114
+ if requires_partial(e.expr):
1115
+ d = '&#x2202;'
1116
+ else:
1117
+ d = self.mathml_tag(e)
1118
+
1119
+ # Determine denominator
1120
+ m = self.dom.createElement('mrow')
1121
+ dim = 0 # Total diff dimension, for numerator
1122
+ for sym, num in reversed(e.variable_count):
1123
+ dim += num
1124
+ if num >= 2:
1125
+ x = self.dom.createElement('msup')
1126
+ xx = self.dom.createElement('mo')
1127
+ xx.appendChild(self.dom.createTextNode(d))
1128
+ x.appendChild(xx)
1129
+ x.appendChild(self._print(num))
1130
+ else:
1131
+ x = self.dom.createElement('mo')
1132
+ x.appendChild(self.dom.createTextNode(d))
1133
+ m.appendChild(x)
1134
+ y = self._print(sym)
1135
+ m.appendChild(y)
1136
+
1137
+ mnum = self.dom.createElement('mrow')
1138
+ if dim >= 2:
1139
+ x = self.dom.createElement('msup')
1140
+ xx = self.dom.createElement('mo')
1141
+ xx.appendChild(self.dom.createTextNode(d))
1142
+ x.appendChild(xx)
1143
+ x.appendChild(self._print(dim))
1144
+ else:
1145
+ x = self.dom.createElement('mo')
1146
+ x.appendChild(self.dom.createTextNode(d))
1147
+
1148
+ mnum.appendChild(x)
1149
+ mrow = self.dom.createElement('mrow')
1150
+ frac = self.dom.createElement('mfrac')
1151
+ frac.appendChild(mnum)
1152
+ frac.appendChild(m)
1153
+ mrow.appendChild(frac)
1154
+
1155
+ # Print function
1156
+ mrow.appendChild(self._print(e.expr))
1157
+
1158
+ return mrow
1159
+
1160
+ def _print_Function(self, e):
1161
+ mrow = self.dom.createElement('mrow')
1162
+ x = self.dom.createElement('mi')
1163
+ if self.mathml_tag(e) == 'log' and self._settings["ln_notation"]:
1164
+ x.appendChild(self.dom.createTextNode('ln'))
1165
+ else:
1166
+ x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
1167
+ y = self.dom.createElement('mfenced')
1168
+ for arg in e.args:
1169
+ y.appendChild(self._print(arg))
1170
+ mrow.appendChild(x)
1171
+ mrow.appendChild(y)
1172
+ return mrow
1173
+
1174
+ def _print_Float(self, expr):
1175
+ # Based off of that in StrPrinter
1176
+ dps = prec_to_dps(expr._prec)
1177
+ str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=True)
1178
+
1179
+ # Must always have a mul symbol (as 2.5 10^{20} just looks odd)
1180
+ # thus we use the number separator
1181
+ separator = self._settings['mul_symbol_mathml_numbers']
1182
+ mrow = self.dom.createElement('mrow')
1183
+ if 'e' in str_real:
1184
+ (mant, exp) = str_real.split('e')
1185
+
1186
+ if exp[0] == '+':
1187
+ exp = exp[1:]
1188
+
1189
+ mn = self.dom.createElement('mn')
1190
+ mn.appendChild(self.dom.createTextNode(mant))
1191
+ mrow.appendChild(mn)
1192
+ mo = self.dom.createElement('mo')
1193
+ mo.appendChild(self.dom.createTextNode(separator))
1194
+ mrow.appendChild(mo)
1195
+ msup = self.dom.createElement('msup')
1196
+ mn = self.dom.createElement('mn')
1197
+ mn.appendChild(self.dom.createTextNode("10"))
1198
+ msup.appendChild(mn)
1199
+ mn = self.dom.createElement('mn')
1200
+ mn.appendChild(self.dom.createTextNode(exp))
1201
+ msup.appendChild(mn)
1202
+ mrow.appendChild(msup)
1203
+ return mrow
1204
+ elif str_real == "+inf":
1205
+ return self._print_Infinity(None)
1206
+ elif str_real == "-inf":
1207
+ return self._print_NegativeInfinity(None)
1208
+ else:
1209
+ mn = self.dom.createElement('mn')
1210
+ mn.appendChild(self.dom.createTextNode(str_real))
1211
+ return mn
1212
+
1213
+ def _print_polylog(self, expr):
1214
+ mrow = self.dom.createElement('mrow')
1215
+ m = self.dom.createElement('msub')
1216
+
1217
+ mi = self.dom.createElement('mi')
1218
+ mi.appendChild(self.dom.createTextNode('Li'))
1219
+ m.appendChild(mi)
1220
+ m.appendChild(self._print(expr.args[0]))
1221
+ mrow.appendChild(m)
1222
+ brac = self.dom.createElement('mfenced')
1223
+ brac.appendChild(self._print(expr.args[1]))
1224
+ mrow.appendChild(brac)
1225
+ return mrow
1226
+
1227
+ def _print_Basic(self, e):
1228
+ mrow = self.dom.createElement('mrow')
1229
+ mi = self.dom.createElement('mi')
1230
+ mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
1231
+ mrow.appendChild(mi)
1232
+ brac = self.dom.createElement('mfenced')
1233
+ for arg in e.args:
1234
+ brac.appendChild(self._print(arg))
1235
+ mrow.appendChild(brac)
1236
+ return mrow
1237
+
1238
+ def _print_Tuple(self, e):
1239
+ mrow = self.dom.createElement('mrow')
1240
+ x = self.dom.createElement('mfenced')
1241
+ for arg in e.args:
1242
+ x.appendChild(self._print(arg))
1243
+ mrow.appendChild(x)
1244
+ return mrow
1245
+
1246
+ def _print_Interval(self, i):
1247
+ mrow = self.dom.createElement('mrow')
1248
+ brac = self.dom.createElement('mfenced')
1249
+ if i.start == i.end:
1250
+ # Most often, this type of Interval is converted to a FiniteSet
1251
+ brac.setAttribute('close', '}')
1252
+ brac.setAttribute('open', '{')
1253
+ brac.appendChild(self._print(i.start))
1254
+ else:
1255
+ if i.right_open:
1256
+ brac.setAttribute('close', ')')
1257
+ else:
1258
+ brac.setAttribute('close', ']')
1259
+
1260
+ if i.left_open:
1261
+ brac.setAttribute('open', '(')
1262
+ else:
1263
+ brac.setAttribute('open', '[')
1264
+ brac.appendChild(self._print(i.start))
1265
+ brac.appendChild(self._print(i.end))
1266
+
1267
+ mrow.appendChild(brac)
1268
+ return mrow
1269
+
1270
+ def _print_Abs(self, expr, exp=None):
1271
+ mrow = self.dom.createElement('mrow')
1272
+ x = self.dom.createElement('mfenced')
1273
+ x.setAttribute('close', '|')
1274
+ x.setAttribute('open', '|')
1275
+ x.appendChild(self._print(expr.args[0]))
1276
+ mrow.appendChild(x)
1277
+ return mrow
1278
+
1279
+ _print_Determinant = _print_Abs
1280
+
1281
+ def _print_re_im(self, c, expr):
1282
+ mrow = self.dom.createElement('mrow')
1283
+ mi = self.dom.createElement('mi')
1284
+ mi.setAttribute('mathvariant', 'fraktur')
1285
+ mi.appendChild(self.dom.createTextNode(c))
1286
+ mrow.appendChild(mi)
1287
+ brac = self.dom.createElement('mfenced')
1288
+ brac.appendChild(self._print(expr))
1289
+ mrow.appendChild(brac)
1290
+ return mrow
1291
+
1292
+ def _print_re(self, expr, exp=None):
1293
+ return self._print_re_im('R', expr.args[0])
1294
+
1295
+ def _print_im(self, expr, exp=None):
1296
+ return self._print_re_im('I', expr.args[0])
1297
+
1298
+ def _print_AssocOp(self, e):
1299
+ mrow = self.dom.createElement('mrow')
1300
+ mi = self.dom.createElement('mi')
1301
+ mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
1302
+ mrow.appendChild(mi)
1303
+ for arg in e.args:
1304
+ mrow.appendChild(self._print(arg))
1305
+ return mrow
1306
+
1307
+ def _print_SetOp(self, expr, symbol, prec):
1308
+ mrow = self.dom.createElement('mrow')
1309
+ mrow.appendChild(self.parenthesize(expr.args[0], prec))
1310
+ for arg in expr.args[1:]:
1311
+ x = self.dom.createElement('mo')
1312
+ x.appendChild(self.dom.createTextNode(symbol))
1313
+ y = self.parenthesize(arg, prec)
1314
+ mrow.appendChild(x)
1315
+ mrow.appendChild(y)
1316
+ return mrow
1317
+
1318
+ def _print_Union(self, expr):
1319
+ prec = PRECEDENCE_TRADITIONAL['Union']
1320
+ return self._print_SetOp(expr, '&#x222A;', prec)
1321
+
1322
+ def _print_Intersection(self, expr):
1323
+ prec = PRECEDENCE_TRADITIONAL['Intersection']
1324
+ return self._print_SetOp(expr, '&#x2229;', prec)
1325
+
1326
+ def _print_Complement(self, expr):
1327
+ prec = PRECEDENCE_TRADITIONAL['Complement']
1328
+ return self._print_SetOp(expr, '&#x2216;', prec)
1329
+
1330
+ def _print_SymmetricDifference(self, expr):
1331
+ prec = PRECEDENCE_TRADITIONAL['SymmetricDifference']
1332
+ return self._print_SetOp(expr, '&#x2206;', prec)
1333
+
1334
+ def _print_ProductSet(self, expr):
1335
+ prec = PRECEDENCE_TRADITIONAL['ProductSet']
1336
+ return self._print_SetOp(expr, '&#x00d7;', prec)
1337
+
1338
+ def _print_FiniteSet(self, s):
1339
+ return self._print_set(s.args)
1340
+
1341
+ def _print_set(self, s):
1342
+ items = sorted(s, key=default_sort_key)
1343
+ brac = self.dom.createElement('mfenced')
1344
+ brac.setAttribute('close', '}')
1345
+ brac.setAttribute('open', '{')
1346
+ for item in items:
1347
+ brac.appendChild(self._print(item))
1348
+ return brac
1349
+
1350
+ _print_frozenset = _print_set
1351
+
1352
+ def _print_LogOp(self, args, symbol):
1353
+ mrow = self.dom.createElement('mrow')
1354
+ if args[0].is_Boolean and not args[0].is_Not:
1355
+ brac = self.dom.createElement('mfenced')
1356
+ brac.appendChild(self._print(args[0]))
1357
+ mrow.appendChild(brac)
1358
+ else:
1359
+ mrow.appendChild(self._print(args[0]))
1360
+ for arg in args[1:]:
1361
+ x = self.dom.createElement('mo')
1362
+ x.appendChild(self.dom.createTextNode(symbol))
1363
+ if arg.is_Boolean and not arg.is_Not:
1364
+ y = self.dom.createElement('mfenced')
1365
+ y.appendChild(self._print(arg))
1366
+ else:
1367
+ y = self._print(arg)
1368
+ mrow.appendChild(x)
1369
+ mrow.appendChild(y)
1370
+ return mrow
1371
+
1372
+ def _print_BasisDependent(self, expr):
1373
+ from sympy.vector import Vector
1374
+
1375
+ if expr == expr.zero:
1376
+ # Not clear if this is ever called
1377
+ return self._print(expr.zero)
1378
+ if isinstance(expr, Vector):
1379
+ items = expr.separate().items()
1380
+ else:
1381
+ items = [(0, expr)]
1382
+
1383
+ mrow = self.dom.createElement('mrow')
1384
+ for system, vect in items:
1385
+ inneritems = list(vect.components.items())
1386
+ inneritems.sort(key = lambda x:x[0].__str__())
1387
+ for i, (k, v) in enumerate(inneritems):
1388
+ if v == 1:
1389
+ if i: # No + for first item
1390
+ mo = self.dom.createElement('mo')
1391
+ mo.appendChild(self.dom.createTextNode('+'))
1392
+ mrow.appendChild(mo)
1393
+ mrow.appendChild(self._print(k))
1394
+ elif v == -1:
1395
+ mo = self.dom.createElement('mo')
1396
+ mo.appendChild(self.dom.createTextNode('-'))
1397
+ mrow.appendChild(mo)
1398
+ mrow.appendChild(self._print(k))
1399
+ else:
1400
+ if i: # No + for first item
1401
+ mo = self.dom.createElement('mo')
1402
+ mo.appendChild(self.dom.createTextNode('+'))
1403
+ mrow.appendChild(mo)
1404
+ mbrac = self.dom.createElement('mfenced')
1405
+ mbrac.appendChild(self._print(v))
1406
+ mrow.appendChild(mbrac)
1407
+ mo = self.dom.createElement('mo')
1408
+ mo.appendChild(self.dom.createTextNode('&InvisibleTimes;'))
1409
+ mrow.appendChild(mo)
1410
+ mrow.appendChild(self._print(k))
1411
+ return mrow
1412
+
1413
+
1414
+ def _print_And(self, expr):
1415
+ args = sorted(expr.args, key=default_sort_key)
1416
+ return self._print_LogOp(args, '&#x2227;')
1417
+
1418
+ def _print_Or(self, expr):
1419
+ args = sorted(expr.args, key=default_sort_key)
1420
+ return self._print_LogOp(args, '&#x2228;')
1421
+
1422
+ def _print_Xor(self, expr):
1423
+ args = sorted(expr.args, key=default_sort_key)
1424
+ return self._print_LogOp(args, '&#x22BB;')
1425
+
1426
+ def _print_Implies(self, expr):
1427
+ return self._print_LogOp(expr.args, '&#x21D2;')
1428
+
1429
+ def _print_Equivalent(self, expr):
1430
+ args = sorted(expr.args, key=default_sort_key)
1431
+ return self._print_LogOp(args, '&#x21D4;')
1432
+
1433
+ def _print_Not(self, e):
1434
+ mrow = self.dom.createElement('mrow')
1435
+ mo = self.dom.createElement('mo')
1436
+ mo.appendChild(self.dom.createTextNode('&#xAC;'))
1437
+ mrow.appendChild(mo)
1438
+ if (e.args[0].is_Boolean):
1439
+ x = self.dom.createElement('mfenced')
1440
+ x.appendChild(self._print(e.args[0]))
1441
+ else:
1442
+ x = self._print(e.args[0])
1443
+ mrow.appendChild(x)
1444
+ return mrow
1445
+
1446
+ def _print_bool(self, e):
1447
+ mi = self.dom.createElement('mi')
1448
+ mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
1449
+ return mi
1450
+
1451
+ _print_BooleanTrue = _print_bool
1452
+ _print_BooleanFalse = _print_bool
1453
+
1454
+ def _print_NoneType(self, e):
1455
+ mi = self.dom.createElement('mi')
1456
+ mi.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
1457
+ return mi
1458
+
1459
+ def _print_Range(self, s):
1460
+ dots = "\u2026"
1461
+ brac = self.dom.createElement('mfenced')
1462
+ brac.setAttribute('close', '}')
1463
+ brac.setAttribute('open', '{')
1464
+
1465
+ if s.start.is_infinite and s.stop.is_infinite:
1466
+ if s.step.is_positive:
1467
+ printset = dots, -1, 0, 1, dots
1468
+ else:
1469
+ printset = dots, 1, 0, -1, dots
1470
+ elif s.start.is_infinite:
1471
+ printset = dots, s[-1] - s.step, s[-1]
1472
+ elif s.stop.is_infinite:
1473
+ it = iter(s)
1474
+ printset = next(it), next(it), dots
1475
+ elif len(s) > 4:
1476
+ it = iter(s)
1477
+ printset = next(it), next(it), dots, s[-1]
1478
+ else:
1479
+ printset = tuple(s)
1480
+
1481
+ for el in printset:
1482
+ if el == dots:
1483
+ mi = self.dom.createElement('mi')
1484
+ mi.appendChild(self.dom.createTextNode(dots))
1485
+ brac.appendChild(mi)
1486
+ else:
1487
+ brac.appendChild(self._print(el))
1488
+
1489
+ return brac
1490
+
1491
+ def _hprint_variadic_function(self, expr):
1492
+ args = sorted(expr.args, key=default_sort_key)
1493
+ mrow = self.dom.createElement('mrow')
1494
+ mo = self.dom.createElement('mo')
1495
+ mo.appendChild(self.dom.createTextNode((str(expr.func)).lower()))
1496
+ mrow.appendChild(mo)
1497
+ brac = self.dom.createElement('mfenced')
1498
+ for symbol in args:
1499
+ brac.appendChild(self._print(symbol))
1500
+ mrow.appendChild(brac)
1501
+ return mrow
1502
+
1503
+ _print_Min = _print_Max = _hprint_variadic_function
1504
+
1505
+ def _print_exp(self, expr):
1506
+ msup = self.dom.createElement('msup')
1507
+ msup.appendChild(self._print_Exp1(None))
1508
+ msup.appendChild(self._print(expr.args[0]))
1509
+ return msup
1510
+
1511
+ def _print_Relational(self, e):
1512
+ mrow = self.dom.createElement('mrow')
1513
+ mrow.appendChild(self._print(e.lhs))
1514
+ x = self.dom.createElement('mo')
1515
+ x.appendChild(self.dom.createTextNode(self.mathml_tag(e)))
1516
+ mrow.appendChild(x)
1517
+ mrow.appendChild(self._print(e.rhs))
1518
+ return mrow
1519
+
1520
+ def _print_int(self, p):
1521
+ dom_element = self.dom.createElement(self.mathml_tag(p))
1522
+ dom_element.appendChild(self.dom.createTextNode(str(p)))
1523
+ return dom_element
1524
+
1525
+ def _print_BaseScalar(self, e):
1526
+ msub = self.dom.createElement('msub')
1527
+ index, system = e._id
1528
+ mi = self.dom.createElement('mi')
1529
+ mi.setAttribute('mathvariant', 'bold')
1530
+ mi.appendChild(self.dom.createTextNode(system._variable_names[index]))
1531
+ msub.appendChild(mi)
1532
+ mi = self.dom.createElement('mi')
1533
+ mi.setAttribute('mathvariant', 'bold')
1534
+ mi.appendChild(self.dom.createTextNode(system._name))
1535
+ msub.appendChild(mi)
1536
+ return msub
1537
+
1538
+ def _print_BaseVector(self, e):
1539
+ msub = self.dom.createElement('msub')
1540
+ index, system = e._id
1541
+ mover = self.dom.createElement('mover')
1542
+ mi = self.dom.createElement('mi')
1543
+ mi.setAttribute('mathvariant', 'bold')
1544
+ mi.appendChild(self.dom.createTextNode(system._vector_names[index]))
1545
+ mover.appendChild(mi)
1546
+ mo = self.dom.createElement('mo')
1547
+ mo.appendChild(self.dom.createTextNode('^'))
1548
+ mover.appendChild(mo)
1549
+ msub.appendChild(mover)
1550
+ mi = self.dom.createElement('mi')
1551
+ mi.setAttribute('mathvariant', 'bold')
1552
+ mi.appendChild(self.dom.createTextNode(system._name))
1553
+ msub.appendChild(mi)
1554
+ return msub
1555
+
1556
+ def _print_VectorZero(self, e):
1557
+ mover = self.dom.createElement('mover')
1558
+ mi = self.dom.createElement('mi')
1559
+ mi.setAttribute('mathvariant', 'bold')
1560
+ mi.appendChild(self.dom.createTextNode("0"))
1561
+ mover.appendChild(mi)
1562
+ mo = self.dom.createElement('mo')
1563
+ mo.appendChild(self.dom.createTextNode('^'))
1564
+ mover.appendChild(mo)
1565
+ return mover
1566
+
1567
+ def _print_Cross(self, expr):
1568
+ mrow = self.dom.createElement('mrow')
1569
+ vec1 = expr._expr1
1570
+ vec2 = expr._expr2
1571
+ mrow.appendChild(self.parenthesize(vec1, PRECEDENCE['Mul']))
1572
+ mo = self.dom.createElement('mo')
1573
+ mo.appendChild(self.dom.createTextNode('&#xD7;'))
1574
+ mrow.appendChild(mo)
1575
+ mrow.appendChild(self.parenthesize(vec2, PRECEDENCE['Mul']))
1576
+ return mrow
1577
+
1578
+ def _print_Curl(self, expr):
1579
+ mrow = self.dom.createElement('mrow')
1580
+ mo = self.dom.createElement('mo')
1581
+ mo.appendChild(self.dom.createTextNode('&#x2207;'))
1582
+ mrow.appendChild(mo)
1583
+ mo = self.dom.createElement('mo')
1584
+ mo.appendChild(self.dom.createTextNode('&#xD7;'))
1585
+ mrow.appendChild(mo)
1586
+ mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
1587
+ return mrow
1588
+
1589
+ def _print_Divergence(self, expr):
1590
+ mrow = self.dom.createElement('mrow')
1591
+ mo = self.dom.createElement('mo')
1592
+ mo.appendChild(self.dom.createTextNode('&#x2207;'))
1593
+ mrow.appendChild(mo)
1594
+ mo = self.dom.createElement('mo')
1595
+ mo.appendChild(self.dom.createTextNode('&#xB7;'))
1596
+ mrow.appendChild(mo)
1597
+ mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
1598
+ return mrow
1599
+
1600
+ def _print_Dot(self, expr):
1601
+ mrow = self.dom.createElement('mrow')
1602
+ vec1 = expr._expr1
1603
+ vec2 = expr._expr2
1604
+ mrow.appendChild(self.parenthesize(vec1, PRECEDENCE['Mul']))
1605
+ mo = self.dom.createElement('mo')
1606
+ mo.appendChild(self.dom.createTextNode('&#xB7;'))
1607
+ mrow.appendChild(mo)
1608
+ mrow.appendChild(self.parenthesize(vec2, PRECEDENCE['Mul']))
1609
+ return mrow
1610
+
1611
+ def _print_Gradient(self, expr):
1612
+ mrow = self.dom.createElement('mrow')
1613
+ mo = self.dom.createElement('mo')
1614
+ mo.appendChild(self.dom.createTextNode('&#x2207;'))
1615
+ mrow.appendChild(mo)
1616
+ mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
1617
+ return mrow
1618
+
1619
+ def _print_Laplacian(self, expr):
1620
+ mrow = self.dom.createElement('mrow')
1621
+ mo = self.dom.createElement('mo')
1622
+ mo.appendChild(self.dom.createTextNode('&#x2206;'))
1623
+ mrow.appendChild(mo)
1624
+ mrow.appendChild(self.parenthesize(expr._expr, PRECEDENCE['Mul']))
1625
+ return mrow
1626
+
1627
+ def _print_Integers(self, e):
1628
+ x = self.dom.createElement('mi')
1629
+ x.setAttribute('mathvariant', 'normal')
1630
+ x.appendChild(self.dom.createTextNode('&#x2124;'))
1631
+ return x
1632
+
1633
+ def _print_Complexes(self, e):
1634
+ x = self.dom.createElement('mi')
1635
+ x.setAttribute('mathvariant', 'normal')
1636
+ x.appendChild(self.dom.createTextNode('&#x2102;'))
1637
+ return x
1638
+
1639
+ def _print_Reals(self, e):
1640
+ x = self.dom.createElement('mi')
1641
+ x.setAttribute('mathvariant', 'normal')
1642
+ x.appendChild(self.dom.createTextNode('&#x211D;'))
1643
+ return x
1644
+
1645
+ def _print_Naturals(self, e):
1646
+ x = self.dom.createElement('mi')
1647
+ x.setAttribute('mathvariant', 'normal')
1648
+ x.appendChild(self.dom.createTextNode('&#x2115;'))
1649
+ return x
1650
+
1651
+ def _print_Naturals0(self, e):
1652
+ sub = self.dom.createElement('msub')
1653
+ x = self.dom.createElement('mi')
1654
+ x.setAttribute('mathvariant', 'normal')
1655
+ x.appendChild(self.dom.createTextNode('&#x2115;'))
1656
+ sub.appendChild(x)
1657
+ sub.appendChild(self._print(S.Zero))
1658
+ return sub
1659
+
1660
+ def _print_SingularityFunction(self, expr):
1661
+ shift = expr.args[0] - expr.args[1]
1662
+ power = expr.args[2]
1663
+ sup = self.dom.createElement('msup')
1664
+ brac = self.dom.createElement('mfenced')
1665
+ brac.setAttribute('close', '\u27e9')
1666
+ brac.setAttribute('open', '\u27e8')
1667
+ brac.appendChild(self._print(shift))
1668
+ sup.appendChild(brac)
1669
+ sup.appendChild(self._print(power))
1670
+ return sup
1671
+
1672
+ def _print_NaN(self, e):
1673
+ x = self.dom.createElement('mi')
1674
+ x.appendChild(self.dom.createTextNode('NaN'))
1675
+ return x
1676
+
1677
+ def _print_number_function(self, e, name):
1678
+ # Print name_arg[0] for one argument or name_arg[0](arg[1])
1679
+ # for more than one argument
1680
+ sub = self.dom.createElement('msub')
1681
+ mi = self.dom.createElement('mi')
1682
+ mi.appendChild(self.dom.createTextNode(name))
1683
+ sub.appendChild(mi)
1684
+ sub.appendChild(self._print(e.args[0]))
1685
+ if len(e.args) == 1:
1686
+ return sub
1687
+ # TODO: copy-pasted from _print_Function: can we do better?
1688
+ mrow = self.dom.createElement('mrow')
1689
+ y = self.dom.createElement('mfenced')
1690
+ for arg in e.args[1:]:
1691
+ y.appendChild(self._print(arg))
1692
+ mrow.appendChild(sub)
1693
+ mrow.appendChild(y)
1694
+ return mrow
1695
+
1696
+ def _print_bernoulli(self, e):
1697
+ return self._print_number_function(e, 'B')
1698
+
1699
+ _print_bell = _print_bernoulli
1700
+
1701
+ def _print_catalan(self, e):
1702
+ return self._print_number_function(e, 'C')
1703
+
1704
+ def _print_euler(self, e):
1705
+ return self._print_number_function(e, 'E')
1706
+
1707
+ def _print_fibonacci(self, e):
1708
+ return self._print_number_function(e, 'F')
1709
+
1710
+ def _print_lucas(self, e):
1711
+ return self._print_number_function(e, 'L')
1712
+
1713
+ def _print_stieltjes(self, e):
1714
+ return self._print_number_function(e, '&#x03B3;')
1715
+
1716
+ def _print_tribonacci(self, e):
1717
+ return self._print_number_function(e, 'T')
1718
+
1719
+ def _print_ComplexInfinity(self, e):
1720
+ x = self.dom.createElement('mover')
1721
+ mo = self.dom.createElement('mo')
1722
+ mo.appendChild(self.dom.createTextNode('&#x221E;'))
1723
+ x.appendChild(mo)
1724
+ mo = self.dom.createElement('mo')
1725
+ mo.appendChild(self.dom.createTextNode('~'))
1726
+ x.appendChild(mo)
1727
+ return x
1728
+
1729
+ def _print_EmptySet(self, e):
1730
+ x = self.dom.createElement('mo')
1731
+ x.appendChild(self.dom.createTextNode('&#x2205;'))
1732
+ return x
1733
+
1734
+ def _print_UniversalSet(self, e):
1735
+ x = self.dom.createElement('mo')
1736
+ x.appendChild(self.dom.createTextNode('&#x1D54C;'))
1737
+ return x
1738
+
1739
+ def _print_Adjoint(self, expr):
1740
+ from sympy.matrices import MatrixSymbol
1741
+ mat = expr.arg
1742
+ sup = self.dom.createElement('msup')
1743
+ if not isinstance(mat, MatrixSymbol):
1744
+ brac = self.dom.createElement('mfenced')
1745
+ brac.appendChild(self._print(mat))
1746
+ sup.appendChild(brac)
1747
+ else:
1748
+ sup.appendChild(self._print(mat))
1749
+ mo = self.dom.createElement('mo')
1750
+ mo.appendChild(self.dom.createTextNode('&#x2020;'))
1751
+ sup.appendChild(mo)
1752
+ return sup
1753
+
1754
+ def _print_Transpose(self, expr):
1755
+ from sympy.matrices import MatrixSymbol
1756
+ mat = expr.arg
1757
+ sup = self.dom.createElement('msup')
1758
+ if not isinstance(mat, MatrixSymbol):
1759
+ brac = self.dom.createElement('mfenced')
1760
+ brac.appendChild(self._print(mat))
1761
+ sup.appendChild(brac)
1762
+ else:
1763
+ sup.appendChild(self._print(mat))
1764
+ mo = self.dom.createElement('mo')
1765
+ mo.appendChild(self.dom.createTextNode('T'))
1766
+ sup.appendChild(mo)
1767
+ return sup
1768
+
1769
+ def _print_Inverse(self, expr):
1770
+ from sympy.matrices import MatrixSymbol
1771
+ mat = expr.arg
1772
+ sup = self.dom.createElement('msup')
1773
+ if not isinstance(mat, MatrixSymbol):
1774
+ brac = self.dom.createElement('mfenced')
1775
+ brac.appendChild(self._print(mat))
1776
+ sup.appendChild(brac)
1777
+ else:
1778
+ sup.appendChild(self._print(mat))
1779
+ sup.appendChild(self._print(-1))
1780
+ return sup
1781
+
1782
+ def _print_MatMul(self, expr):
1783
+ from sympy.matrices.expressions.matmul import MatMul
1784
+
1785
+ x = self.dom.createElement('mrow')
1786
+ args = expr.args
1787
+ if isinstance(args[0], Mul):
1788
+ args = args[0].as_ordered_factors() + list(args[1:])
1789
+ else:
1790
+ args = list(args)
1791
+
1792
+ if isinstance(expr, MatMul) and expr.could_extract_minus_sign():
1793
+ if args[0] == -1:
1794
+ args = args[1:]
1795
+ else:
1796
+ args[0] = -args[0]
1797
+ mo = self.dom.createElement('mo')
1798
+ mo.appendChild(self.dom.createTextNode('-'))
1799
+ x.appendChild(mo)
1800
+
1801
+ for arg in args[:-1]:
1802
+ x.appendChild(self.parenthesize(arg, precedence_traditional(expr),
1803
+ False))
1804
+ mo = self.dom.createElement('mo')
1805
+ mo.appendChild(self.dom.createTextNode('&InvisibleTimes;'))
1806
+ x.appendChild(mo)
1807
+ x.appendChild(self.parenthesize(args[-1], precedence_traditional(expr),
1808
+ False))
1809
+ return x
1810
+
1811
+ def _print_MatPow(self, expr):
1812
+ from sympy.matrices import MatrixSymbol
1813
+ base, exp = expr.base, expr.exp
1814
+ sup = self.dom.createElement('msup')
1815
+ if not isinstance(base, MatrixSymbol):
1816
+ brac = self.dom.createElement('mfenced')
1817
+ brac.appendChild(self._print(base))
1818
+ sup.appendChild(brac)
1819
+ else:
1820
+ sup.appendChild(self._print(base))
1821
+ sup.appendChild(self._print(exp))
1822
+ return sup
1823
+
1824
+ def _print_HadamardProduct(self, expr):
1825
+ x = self.dom.createElement('mrow')
1826
+ args = expr.args
1827
+ for arg in args[:-1]:
1828
+ x.appendChild(
1829
+ self.parenthesize(arg, precedence_traditional(expr), False))
1830
+ mo = self.dom.createElement('mo')
1831
+ mo.appendChild(self.dom.createTextNode('&#x2218;'))
1832
+ x.appendChild(mo)
1833
+ x.appendChild(
1834
+ self.parenthesize(args[-1], precedence_traditional(expr), False))
1835
+ return x
1836
+
1837
+ def _print_ZeroMatrix(self, Z):
1838
+ x = self.dom.createElement('mn')
1839
+ x.appendChild(self.dom.createTextNode('&#x1D7D8'))
1840
+ return x
1841
+
1842
+ def _print_OneMatrix(self, Z):
1843
+ x = self.dom.createElement('mn')
1844
+ x.appendChild(self.dom.createTextNode('&#x1D7D9'))
1845
+ return x
1846
+
1847
+ def _print_Identity(self, I):
1848
+ x = self.dom.createElement('mi')
1849
+ x.appendChild(self.dom.createTextNode('&#x1D540;'))
1850
+ return x
1851
+
1852
+ def _print_floor(self, e):
1853
+ mrow = self.dom.createElement('mrow')
1854
+ x = self.dom.createElement('mfenced')
1855
+ x.setAttribute('close', '\u230B')
1856
+ x.setAttribute('open', '\u230A')
1857
+ x.appendChild(self._print(e.args[0]))
1858
+ mrow.appendChild(x)
1859
+ return mrow
1860
+
1861
+ def _print_ceiling(self, e):
1862
+ mrow = self.dom.createElement('mrow')
1863
+ x = self.dom.createElement('mfenced')
1864
+ x.setAttribute('close', '\u2309')
1865
+ x.setAttribute('open', '\u2308')
1866
+ x.appendChild(self._print(e.args[0]))
1867
+ mrow.appendChild(x)
1868
+ return mrow
1869
+
1870
+ def _print_Lambda(self, e):
1871
+ x = self.dom.createElement('mfenced')
1872
+ mrow = self.dom.createElement('mrow')
1873
+ symbols = e.args[0]
1874
+ if len(symbols) == 1:
1875
+ symbols = self._print(symbols[0])
1876
+ else:
1877
+ symbols = self._print(symbols)
1878
+ mrow.appendChild(symbols)
1879
+ mo = self.dom.createElement('mo')
1880
+ mo.appendChild(self.dom.createTextNode('&#x21A6;'))
1881
+ mrow.appendChild(mo)
1882
+ mrow.appendChild(self._print(e.args[1]))
1883
+ x.appendChild(mrow)
1884
+ return x
1885
+
1886
+ def _print_tuple(self, e):
1887
+ x = self.dom.createElement('mfenced')
1888
+ for i in e:
1889
+ x.appendChild(self._print(i))
1890
+ return x
1891
+
1892
+ def _print_IndexedBase(self, e):
1893
+ return self._print(e.label)
1894
+
1895
+ def _print_Indexed(self, e):
1896
+ x = self.dom.createElement('msub')
1897
+ x.appendChild(self._print(e.base))
1898
+ if len(e.indices) == 1:
1899
+ x.appendChild(self._print(e.indices[0]))
1900
+ return x
1901
+ x.appendChild(self._print(e.indices))
1902
+ return x
1903
+
1904
+ def _print_MatrixElement(self, e):
1905
+ x = self.dom.createElement('msub')
1906
+ x.appendChild(self.parenthesize(e.parent, PRECEDENCE["Atom"], strict = True))
1907
+ brac = self.dom.createElement('mfenced')
1908
+ brac.setAttribute("close", "")
1909
+ brac.setAttribute("open", "")
1910
+ for i in e.indices:
1911
+ brac.appendChild(self._print(i))
1912
+ x.appendChild(brac)
1913
+ return x
1914
+
1915
+ def _print_elliptic_f(self, e):
1916
+ x = self.dom.createElement('mrow')
1917
+ mi = self.dom.createElement('mi')
1918
+ mi.appendChild(self.dom.createTextNode('&#x1d5a5;'))
1919
+ x.appendChild(mi)
1920
+ y = self.dom.createElement('mfenced')
1921
+ y.setAttribute("separators", "|")
1922
+ for i in e.args:
1923
+ y.appendChild(self._print(i))
1924
+ x.appendChild(y)
1925
+ return x
1926
+
1927
+ def _print_elliptic_e(self, e):
1928
+ x = self.dom.createElement('mrow')
1929
+ mi = self.dom.createElement('mi')
1930
+ mi.appendChild(self.dom.createTextNode('&#x1d5a4;'))
1931
+ x.appendChild(mi)
1932
+ y = self.dom.createElement('mfenced')
1933
+ y.setAttribute("separators", "|")
1934
+ for i in e.args:
1935
+ y.appendChild(self._print(i))
1936
+ x.appendChild(y)
1937
+ return x
1938
+
1939
+ def _print_elliptic_pi(self, e):
1940
+ x = self.dom.createElement('mrow')
1941
+ mi = self.dom.createElement('mi')
1942
+ mi.appendChild(self.dom.createTextNode('&#x1d6f1;'))
1943
+ x.appendChild(mi)
1944
+ y = self.dom.createElement('mfenced')
1945
+ if len(e.args) == 2:
1946
+ y.setAttribute("separators", "|")
1947
+ else:
1948
+ y.setAttribute("separators", ";|")
1949
+ for i in e.args:
1950
+ y.appendChild(self._print(i))
1951
+ x.appendChild(y)
1952
+ return x
1953
+
1954
+ def _print_Ei(self, e):
1955
+ x = self.dom.createElement('mrow')
1956
+ mi = self.dom.createElement('mi')
1957
+ mi.appendChild(self.dom.createTextNode('Ei'))
1958
+ x.appendChild(mi)
1959
+ x.appendChild(self._print(e.args))
1960
+ return x
1961
+
1962
+ def _print_expint(self, e):
1963
+ x = self.dom.createElement('mrow')
1964
+ y = self.dom.createElement('msub')
1965
+ mo = self.dom.createElement('mo')
1966
+ mo.appendChild(self.dom.createTextNode('E'))
1967
+ y.appendChild(mo)
1968
+ y.appendChild(self._print(e.args[0]))
1969
+ x.appendChild(y)
1970
+ x.appendChild(self._print(e.args[1:]))
1971
+ return x
1972
+
1973
+ def _print_jacobi(self, e):
1974
+ x = self.dom.createElement('mrow')
1975
+ y = self.dom.createElement('msubsup')
1976
+ mo = self.dom.createElement('mo')
1977
+ mo.appendChild(self.dom.createTextNode('P'))
1978
+ y.appendChild(mo)
1979
+ y.appendChild(self._print(e.args[0]))
1980
+ y.appendChild(self._print(e.args[1:3]))
1981
+ x.appendChild(y)
1982
+ x.appendChild(self._print(e.args[3:]))
1983
+ return x
1984
+
1985
+ def _print_gegenbauer(self, e):
1986
+ x = self.dom.createElement('mrow')
1987
+ y = self.dom.createElement('msubsup')
1988
+ mo = self.dom.createElement('mo')
1989
+ mo.appendChild(self.dom.createTextNode('C'))
1990
+ y.appendChild(mo)
1991
+ y.appendChild(self._print(e.args[0]))
1992
+ y.appendChild(self._print(e.args[1:2]))
1993
+ x.appendChild(y)
1994
+ x.appendChild(self._print(e.args[2:]))
1995
+ return x
1996
+
1997
+ def _print_chebyshevt(self, e):
1998
+ x = self.dom.createElement('mrow')
1999
+ y = self.dom.createElement('msub')
2000
+ mo = self.dom.createElement('mo')
2001
+ mo.appendChild(self.dom.createTextNode('T'))
2002
+ y.appendChild(mo)
2003
+ y.appendChild(self._print(e.args[0]))
2004
+ x.appendChild(y)
2005
+ x.appendChild(self._print(e.args[1:]))
2006
+ return x
2007
+
2008
+ def _print_chebyshevu(self, e):
2009
+ x = self.dom.createElement('mrow')
2010
+ y = self.dom.createElement('msub')
2011
+ mo = self.dom.createElement('mo')
2012
+ mo.appendChild(self.dom.createTextNode('U'))
2013
+ y.appendChild(mo)
2014
+ y.appendChild(self._print(e.args[0]))
2015
+ x.appendChild(y)
2016
+ x.appendChild(self._print(e.args[1:]))
2017
+ return x
2018
+
2019
+ def _print_legendre(self, e):
2020
+ x = self.dom.createElement('mrow')
2021
+ y = self.dom.createElement('msub')
2022
+ mo = self.dom.createElement('mo')
2023
+ mo.appendChild(self.dom.createTextNode('P'))
2024
+ y.appendChild(mo)
2025
+ y.appendChild(self._print(e.args[0]))
2026
+ x.appendChild(y)
2027
+ x.appendChild(self._print(e.args[1:]))
2028
+ return x
2029
+
2030
+ def _print_assoc_legendre(self, e):
2031
+ x = self.dom.createElement('mrow')
2032
+ y = self.dom.createElement('msubsup')
2033
+ mo = self.dom.createElement('mo')
2034
+ mo.appendChild(self.dom.createTextNode('P'))
2035
+ y.appendChild(mo)
2036
+ y.appendChild(self._print(e.args[0]))
2037
+ y.appendChild(self._print(e.args[1:2]))
2038
+ x.appendChild(y)
2039
+ x.appendChild(self._print(e.args[2:]))
2040
+ return x
2041
+
2042
+ def _print_laguerre(self, e):
2043
+ x = self.dom.createElement('mrow')
2044
+ y = self.dom.createElement('msub')
2045
+ mo = self.dom.createElement('mo')
2046
+ mo.appendChild(self.dom.createTextNode('L'))
2047
+ y.appendChild(mo)
2048
+ y.appendChild(self._print(e.args[0]))
2049
+ x.appendChild(y)
2050
+ x.appendChild(self._print(e.args[1:]))
2051
+ return x
2052
+
2053
+ def _print_assoc_laguerre(self, e):
2054
+ x = self.dom.createElement('mrow')
2055
+ y = self.dom.createElement('msubsup')
2056
+ mo = self.dom.createElement('mo')
2057
+ mo.appendChild(self.dom.createTextNode('L'))
2058
+ y.appendChild(mo)
2059
+ y.appendChild(self._print(e.args[0]))
2060
+ y.appendChild(self._print(e.args[1:2]))
2061
+ x.appendChild(y)
2062
+ x.appendChild(self._print(e.args[2:]))
2063
+ return x
2064
+
2065
+ def _print_hermite(self, e):
2066
+ x = self.dom.createElement('mrow')
2067
+ y = self.dom.createElement('msub')
2068
+ mo = self.dom.createElement('mo')
2069
+ mo.appendChild(self.dom.createTextNode('H'))
2070
+ y.appendChild(mo)
2071
+ y.appendChild(self._print(e.args[0]))
2072
+ x.appendChild(y)
2073
+ x.appendChild(self._print(e.args[1:]))
2074
+ return x
2075
+
2076
+
2077
+ @print_function(MathMLPrinterBase)
2078
+ def mathml(expr, printer='content', **settings):
2079
+ """Returns the MathML representation of expr. If printer is presentation
2080
+ then prints Presentation MathML else prints content MathML.
2081
+ """
2082
+ if printer == 'presentation':
2083
+ return MathMLPresentationPrinter(settings).doprint(expr)
2084
+ else:
2085
+ return MathMLContentPrinter(settings).doprint(expr)
2086
+
2087
+
2088
+ def print_mathml(expr, printer='content', **settings):
2089
+ """
2090
+ Prints a pretty representation of the MathML code for expr. If printer is
2091
+ presentation then prints Presentation MathML else prints content MathML.
2092
+
2093
+ Examples
2094
+ ========
2095
+
2096
+ >>> ##
2097
+ >>> from sympy import print_mathml
2098
+ >>> from sympy.abc import x
2099
+ >>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE
2100
+ <apply>
2101
+ <plus/>
2102
+ <ci>x</ci>
2103
+ <cn>1</cn>
2104
+ </apply>
2105
+ >>> print_mathml(x+1, printer='presentation')
2106
+ <mrow>
2107
+ <mi>x</mi>
2108
+ <mo>+</mo>
2109
+ <mn>1</mn>
2110
+ </mrow>
2111
+
2112
+ """
2113
+ if printer == 'presentation':
2114
+ s = MathMLPresentationPrinter(settings)
2115
+ else:
2116
+ s = MathMLContentPrinter(settings)
2117
+ xml = s._print(sympify(expr))
2118
+ s.apply_patch()
2119
+ pretty_xml = xml.toprettyxml()
2120
+ s.restore_patch()
2121
+
2122
+ print(pretty_xml)
2123
+
2124
+
2125
+ # For backward compatibility
2126
+ MathMLPrinter = MathMLContentPrinter
env-llmeval/lib/python3.10/site-packages/sympy/printing/numpy.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S
2
+ from sympy.core.function import Lambda
3
+ from sympy.core.power import Pow
4
+ from .pycode import PythonCodePrinter, _known_functions_math, _print_known_const, _print_known_func, _unpack_integral_limits, ArrayPrinter
5
+ from .codeprinter import CodePrinter
6
+
7
+
8
+ _not_in_numpy = 'erf erfc factorial gamma loggamma'.split()
9
+ _in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy]
10
+ _known_functions_numpy = dict(_in_numpy, **{
11
+ 'acos': 'arccos',
12
+ 'acosh': 'arccosh',
13
+ 'asin': 'arcsin',
14
+ 'asinh': 'arcsinh',
15
+ 'atan': 'arctan',
16
+ 'atan2': 'arctan2',
17
+ 'atanh': 'arctanh',
18
+ 'exp2': 'exp2',
19
+ 'sign': 'sign',
20
+ 'logaddexp': 'logaddexp',
21
+ 'logaddexp2': 'logaddexp2',
22
+ })
23
+ _known_constants_numpy = {
24
+ 'Exp1': 'e',
25
+ 'Pi': 'pi',
26
+ 'EulerGamma': 'euler_gamma',
27
+ 'NaN': 'nan',
28
+ 'Infinity': 'PINF',
29
+ 'NegativeInfinity': 'NINF'
30
+ }
31
+
32
+ _numpy_known_functions = {k: 'numpy.' + v for k, v in _known_functions_numpy.items()}
33
+ _numpy_known_constants = {k: 'numpy.' + v for k, v in _known_constants_numpy.items()}
34
+
35
+ class NumPyPrinter(ArrayPrinter, PythonCodePrinter):
36
+ """
37
+ Numpy printer which handles vectorized piecewise functions,
38
+ logical operators, etc.
39
+ """
40
+
41
+ _module = 'numpy'
42
+ _kf = _numpy_known_functions
43
+ _kc = _numpy_known_constants
44
+
45
+ def __init__(self, settings=None):
46
+ """
47
+ `settings` is passed to CodePrinter.__init__()
48
+ `module` specifies the array module to use, currently 'NumPy', 'CuPy'
49
+ or 'JAX'.
50
+ """
51
+ self.language = "Python with {}".format(self._module)
52
+ self.printmethod = "_{}code".format(self._module)
53
+
54
+ self._kf = {**PythonCodePrinter._kf, **self._kf}
55
+
56
+ super().__init__(settings=settings)
57
+
58
+
59
+ def _print_seq(self, seq):
60
+ "General sequence printer: converts to tuple"
61
+ # Print tuples here instead of lists because numba supports
62
+ # tuples in nopython mode.
63
+ delimiter=', '
64
+ return '({},)'.format(delimiter.join(self._print(item) for item in seq))
65
+
66
+ def _print_MatMul(self, expr):
67
+ "Matrix multiplication printer"
68
+ if expr.as_coeff_matrices()[0] is not S.One:
69
+ expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])]
70
+ return '({})'.format(').dot('.join(self._print(i) for i in expr_list))
71
+ return '({})'.format(').dot('.join(self._print(i) for i in expr.args))
72
+
73
+ def _print_MatPow(self, expr):
74
+ "Matrix power printer"
75
+ return '{}({}, {})'.format(self._module_format(self._module + '.linalg.matrix_power'),
76
+ self._print(expr.args[0]), self._print(expr.args[1]))
77
+
78
+ def _print_Inverse(self, expr):
79
+ "Matrix inverse printer"
80
+ return '{}({})'.format(self._module_format(self._module + '.linalg.inv'),
81
+ self._print(expr.args[0]))
82
+
83
+ def _print_DotProduct(self, expr):
84
+ # DotProduct allows any shape order, but numpy.dot does matrix
85
+ # multiplication, so we have to make sure it gets 1 x n by n x 1.
86
+ arg1, arg2 = expr.args
87
+ if arg1.shape[0] != 1:
88
+ arg1 = arg1.T
89
+ if arg2.shape[1] != 1:
90
+ arg2 = arg2.T
91
+
92
+ return "%s(%s, %s)" % (self._module_format(self._module + '.dot'),
93
+ self._print(arg1),
94
+ self._print(arg2))
95
+
96
+ def _print_MatrixSolve(self, expr):
97
+ return "%s(%s, %s)" % (self._module_format(self._module + '.linalg.solve'),
98
+ self._print(expr.matrix),
99
+ self._print(expr.vector))
100
+
101
+ def _print_ZeroMatrix(self, expr):
102
+ return '{}({})'.format(self._module_format(self._module + '.zeros'),
103
+ self._print(expr.shape))
104
+
105
+ def _print_OneMatrix(self, expr):
106
+ return '{}({})'.format(self._module_format(self._module + '.ones'),
107
+ self._print(expr.shape))
108
+
109
+ def _print_FunctionMatrix(self, expr):
110
+ from sympy.abc import i, j
111
+ lamda = expr.lamda
112
+ if not isinstance(lamda, Lambda):
113
+ lamda = Lambda((i, j), lamda(i, j))
114
+ return '{}(lambda {}: {}, {})'.format(self._module_format(self._module + '.fromfunction'),
115
+ ', '.join(self._print(arg) for arg in lamda.args[0]),
116
+ self._print(lamda.args[1]), self._print(expr.shape))
117
+
118
+ def _print_HadamardProduct(self, expr):
119
+ func = self._module_format(self._module + '.multiply')
120
+ return ''.join('{}({}, '.format(func, self._print(arg)) \
121
+ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
122
+ ')' * (len(expr.args) - 1))
123
+
124
+ def _print_KroneckerProduct(self, expr):
125
+ func = self._module_format(self._module + '.kron')
126
+ return ''.join('{}({}, '.format(func, self._print(arg)) \
127
+ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),
128
+ ')' * (len(expr.args) - 1))
129
+
130
+ def _print_Adjoint(self, expr):
131
+ return '{}({}({}))'.format(
132
+ self._module_format(self._module + '.conjugate'),
133
+ self._module_format(self._module + '.transpose'),
134
+ self._print(expr.args[0]))
135
+
136
+ def _print_DiagonalOf(self, expr):
137
+ vect = '{}({})'.format(
138
+ self._module_format(self._module + '.diag'),
139
+ self._print(expr.arg))
140
+ return '{}({}, (-1, 1))'.format(
141
+ self._module_format(self._module + '.reshape'), vect)
142
+
143
+ def _print_DiagMatrix(self, expr):
144
+ return '{}({})'.format(self._module_format(self._module + '.diagflat'),
145
+ self._print(expr.args[0]))
146
+
147
+ def _print_DiagonalMatrix(self, expr):
148
+ return '{}({}, {}({}, {}))'.format(self._module_format(self._module + '.multiply'),
149
+ self._print(expr.arg), self._module_format(self._module + '.eye'),
150
+ self._print(expr.shape[0]), self._print(expr.shape[1]))
151
+
152
+ def _print_Piecewise(self, expr):
153
+ "Piecewise function printer"
154
+ from sympy.logic.boolalg import ITE, simplify_logic
155
+ def print_cond(cond):
156
+ """ Problem having an ITE in the cond. """
157
+ if cond.has(ITE):
158
+ return self._print(simplify_logic(cond))
159
+ else:
160
+ return self._print(cond)
161
+ exprs = '[{}]'.format(','.join(self._print(arg.expr) for arg in expr.args))
162
+ conds = '[{}]'.format(','.join(print_cond(arg.cond) for arg in expr.args))
163
+ # If [default_value, True] is a (expr, cond) sequence in a Piecewise object
164
+ # it will behave the same as passing the 'default' kwarg to select()
165
+ # *as long as* it is the last element in expr.args.
166
+ # If this is not the case, it may be triggered prematurely.
167
+ return '{}({}, {}, default={})'.format(
168
+ self._module_format(self._module + '.select'), conds, exprs,
169
+ self._print(S.NaN))
170
+
171
+ def _print_Relational(self, expr):
172
+ "Relational printer for Equality and Unequality"
173
+ op = {
174
+ '==' :'equal',
175
+ '!=' :'not_equal',
176
+ '<' :'less',
177
+ '<=' :'less_equal',
178
+ '>' :'greater',
179
+ '>=' :'greater_equal',
180
+ }
181
+ if expr.rel_op in op:
182
+ lhs = self._print(expr.lhs)
183
+ rhs = self._print(expr.rhs)
184
+ return '{op}({lhs}, {rhs})'.format(op=self._module_format(self._module + '.'+op[expr.rel_op]),
185
+ lhs=lhs, rhs=rhs)
186
+ return super()._print_Relational(expr)
187
+
188
+ def _print_And(self, expr):
189
+ "Logical And printer"
190
+ # We have to override LambdaPrinter because it uses Python 'and' keyword.
191
+ # If LambdaPrinter didn't define it, we could use StrPrinter's
192
+ # version of the function and add 'logical_and' to NUMPY_TRANSLATIONS.
193
+ return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_and'), ','.join(self._print(i) for i in expr.args))
194
+
195
+ def _print_Or(self, expr):
196
+ "Logical Or printer"
197
+ # We have to override LambdaPrinter because it uses Python 'or' keyword.
198
+ # If LambdaPrinter didn't define it, we could use StrPrinter's
199
+ # version of the function and add 'logical_or' to NUMPY_TRANSLATIONS.
200
+ return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_or'), ','.join(self._print(i) for i in expr.args))
201
+
202
+ def _print_Not(self, expr):
203
+ "Logical Not printer"
204
+ # We have to override LambdaPrinter because it uses Python 'not' keyword.
205
+ # If LambdaPrinter didn't define it, we would still have to define our
206
+ # own because StrPrinter doesn't define it.
207
+ return '{}({})'.format(self._module_format(self._module + '.logical_not'), ','.join(self._print(i) for i in expr.args))
208
+
209
+ def _print_Pow(self, expr, rational=False):
210
+ # XXX Workaround for negative integer power error
211
+ if expr.exp.is_integer and expr.exp.is_negative:
212
+ expr = Pow(expr.base, expr.exp.evalf(), evaluate=False)
213
+ return self._hprint_Pow(expr, rational=rational, sqrt=self._module + '.sqrt')
214
+
215
+ def _print_Min(self, expr):
216
+ return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amin'), ','.join(self._print(i) for i in expr.args))
217
+
218
+ def _print_Max(self, expr):
219
+ return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amax'), ','.join(self._print(i) for i in expr.args))
220
+
221
+ def _print_arg(self, expr):
222
+ return "%s(%s)" % (self._module_format(self._module + '.angle'), self._print(expr.args[0]))
223
+
224
+ def _print_im(self, expr):
225
+ return "%s(%s)" % (self._module_format(self._module + '.imag'), self._print(expr.args[0]))
226
+
227
+ def _print_Mod(self, expr):
228
+ return "%s(%s)" % (self._module_format(self._module + '.mod'), ', '.join(
229
+ (self._print(arg) for arg in expr.args)))
230
+
231
+ def _print_re(self, expr):
232
+ return "%s(%s)" % (self._module_format(self._module + '.real'), self._print(expr.args[0]))
233
+
234
+ def _print_sinc(self, expr):
235
+ return "%s(%s)" % (self._module_format(self._module + '.sinc'), self._print(expr.args[0]/S.Pi))
236
+
237
+ def _print_MatrixBase(self, expr):
238
+ func = self.known_functions.get(expr.__class__.__name__, None)
239
+ if func is None:
240
+ func = self._module_format(self._module + '.array')
241
+ return "%s(%s)" % (func, self._print(expr.tolist()))
242
+
243
+ def _print_Identity(self, expr):
244
+ shape = expr.shape
245
+ if all(dim.is_Integer for dim in shape):
246
+ return "%s(%s)" % (self._module_format(self._module + '.eye'), self._print(expr.shape[0]))
247
+ else:
248
+ raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices")
249
+
250
+ def _print_BlockMatrix(self, expr):
251
+ return '{}({})'.format(self._module_format(self._module + '.block'),
252
+ self._print(expr.args[0].tolist()))
253
+
254
+ def _print_NDimArray(self, expr):
255
+ if len(expr.shape) == 1:
256
+ return self._module + '.array(' + self._print(expr.args[0]) + ')'
257
+ if len(expr.shape) == 2:
258
+ return self._print(expr.tomatrix())
259
+ # Should be possible to extend to more dimensions
260
+ return CodePrinter._print_not_supported(self, expr)
261
+
262
+ _add = "add"
263
+ _einsum = "einsum"
264
+ _transpose = "transpose"
265
+ _ones = "ones"
266
+ _zeros = "zeros"
267
+
268
+ _print_lowergamma = CodePrinter._print_not_supported
269
+ _print_uppergamma = CodePrinter._print_not_supported
270
+ _print_fresnelc = CodePrinter._print_not_supported
271
+ _print_fresnels = CodePrinter._print_not_supported
272
+
273
+ for func in _numpy_known_functions:
274
+ setattr(NumPyPrinter, f'_print_{func}', _print_known_func)
275
+
276
+ for const in _numpy_known_constants:
277
+ setattr(NumPyPrinter, f'_print_{const}', _print_known_const)
278
+
279
+
280
+ _known_functions_scipy_special = {
281
+ 'Ei': 'expi',
282
+ 'erf': 'erf',
283
+ 'erfc': 'erfc',
284
+ 'besselj': 'jv',
285
+ 'bessely': 'yv',
286
+ 'besseli': 'iv',
287
+ 'besselk': 'kv',
288
+ 'cosm1': 'cosm1',
289
+ 'powm1': 'powm1',
290
+ 'factorial': 'factorial',
291
+ 'gamma': 'gamma',
292
+ 'loggamma': 'gammaln',
293
+ 'digamma': 'psi',
294
+ 'polygamma': 'polygamma',
295
+ 'RisingFactorial': 'poch',
296
+ 'jacobi': 'eval_jacobi',
297
+ 'gegenbauer': 'eval_gegenbauer',
298
+ 'chebyshevt': 'eval_chebyt',
299
+ 'chebyshevu': 'eval_chebyu',
300
+ 'legendre': 'eval_legendre',
301
+ 'hermite': 'eval_hermite',
302
+ 'laguerre': 'eval_laguerre',
303
+ 'assoc_laguerre': 'eval_genlaguerre',
304
+ 'beta': 'beta',
305
+ 'LambertW' : 'lambertw',
306
+ }
307
+
308
+ _known_constants_scipy_constants = {
309
+ 'GoldenRatio': 'golden_ratio',
310
+ 'Pi': 'pi',
311
+ }
312
+ _scipy_known_functions = {k : "scipy.special." + v for k, v in _known_functions_scipy_special.items()}
313
+ _scipy_known_constants = {k : "scipy.constants." + v for k, v in _known_constants_scipy_constants.items()}
314
+
315
+ class SciPyPrinter(NumPyPrinter):
316
+
317
+ _kf = {**NumPyPrinter._kf, **_scipy_known_functions}
318
+ _kc = {**NumPyPrinter._kc, **_scipy_known_constants}
319
+
320
+ def __init__(self, settings=None):
321
+ super().__init__(settings=settings)
322
+ self.language = "Python with SciPy and NumPy"
323
+
324
+ def _print_SparseRepMatrix(self, expr):
325
+ i, j, data = [], [], []
326
+ for (r, c), v in expr.todok().items():
327
+ i.append(r)
328
+ j.append(c)
329
+ data.append(v)
330
+
331
+ return "{name}(({data}, ({i}, {j})), shape={shape})".format(
332
+ name=self._module_format('scipy.sparse.coo_matrix'),
333
+ data=data, i=i, j=j, shape=expr.shape
334
+ )
335
+
336
+ _print_ImmutableSparseMatrix = _print_SparseRepMatrix
337
+
338
+ # SciPy's lpmv has a different order of arguments from assoc_legendre
339
+ def _print_assoc_legendre(self, expr):
340
+ return "{0}({2}, {1}, {3})".format(
341
+ self._module_format('scipy.special.lpmv'),
342
+ self._print(expr.args[0]),
343
+ self._print(expr.args[1]),
344
+ self._print(expr.args[2]))
345
+
346
+ def _print_lowergamma(self, expr):
347
+ return "{0}({2})*{1}({2}, {3})".format(
348
+ self._module_format('scipy.special.gamma'),
349
+ self._module_format('scipy.special.gammainc'),
350
+ self._print(expr.args[0]),
351
+ self._print(expr.args[1]))
352
+
353
+ def _print_uppergamma(self, expr):
354
+ return "{0}({2})*{1}({2}, {3})".format(
355
+ self._module_format('scipy.special.gamma'),
356
+ self._module_format('scipy.special.gammaincc'),
357
+ self._print(expr.args[0]),
358
+ self._print(expr.args[1]))
359
+
360
+ def _print_betainc(self, expr):
361
+ betainc = self._module_format('scipy.special.betainc')
362
+ beta = self._module_format('scipy.special.beta')
363
+ args = [self._print(arg) for arg in expr.args]
364
+ return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \
365
+ * {beta}({args[0]}, {args[1]})"
366
+
367
+ def _print_betainc_regularized(self, expr):
368
+ return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format(
369
+ self._module_format('scipy.special.betainc'),
370
+ self._print(expr.args[0]),
371
+ self._print(expr.args[1]),
372
+ self._print(expr.args[2]),
373
+ self._print(expr.args[3]))
374
+
375
+ def _print_fresnels(self, expr):
376
+ return "{}({})[0]".format(
377
+ self._module_format("scipy.special.fresnel"),
378
+ self._print(expr.args[0]))
379
+
380
+ def _print_fresnelc(self, expr):
381
+ return "{}({})[1]".format(
382
+ self._module_format("scipy.special.fresnel"),
383
+ self._print(expr.args[0]))
384
+
385
+ def _print_airyai(self, expr):
386
+ return "{}({})[0]".format(
387
+ self._module_format("scipy.special.airy"),
388
+ self._print(expr.args[0]))
389
+
390
+ def _print_airyaiprime(self, expr):
391
+ return "{}({})[1]".format(
392
+ self._module_format("scipy.special.airy"),
393
+ self._print(expr.args[0]))
394
+
395
+ def _print_airybi(self, expr):
396
+ return "{}({})[2]".format(
397
+ self._module_format("scipy.special.airy"),
398
+ self._print(expr.args[0]))
399
+
400
+ def _print_airybiprime(self, expr):
401
+ return "{}({})[3]".format(
402
+ self._module_format("scipy.special.airy"),
403
+ self._print(expr.args[0]))
404
+
405
+ def _print_bernoulli(self, expr):
406
+ # scipy's bernoulli is inconsistent with SymPy's so rewrite
407
+ return self._print(expr._eval_rewrite_as_zeta(*expr.args))
408
+
409
+ def _print_harmonic(self, expr):
410
+ return self._print(expr._eval_rewrite_as_zeta(*expr.args))
411
+
412
+ def _print_Integral(self, e):
413
+ integration_vars, limits = _unpack_integral_limits(e)
414
+
415
+ if len(limits) == 1:
416
+ # nicer (but not necessary) to prefer quad over nquad for 1D case
417
+ module_str = self._module_format("scipy.integrate.quad")
418
+ limit_str = "%s, %s" % tuple(map(self._print, limits[0]))
419
+ else:
420
+ module_str = self._module_format("scipy.integrate.nquad")
421
+ limit_str = "({})".format(", ".join(
422
+ "(%s, %s)" % tuple(map(self._print, l)) for l in limits))
423
+
424
+ return "{}(lambda {}: {}, {})[0]".format(
425
+ module_str,
426
+ ", ".join(map(self._print, integration_vars)),
427
+ self._print(e.args[0]),
428
+ limit_str)
429
+
430
+ def _print_Si(self, expr):
431
+ return "{}({})[0]".format(
432
+ self._module_format("scipy.special.sici"),
433
+ self._print(expr.args[0]))
434
+
435
+ def _print_Ci(self, expr):
436
+ return "{}({})[1]".format(
437
+ self._module_format("scipy.special.sici"),
438
+ self._print(expr.args[0]))
439
+
440
+ for func in _scipy_known_functions:
441
+ setattr(SciPyPrinter, f'_print_{func}', _print_known_func)
442
+
443
+ for const in _scipy_known_constants:
444
+ setattr(SciPyPrinter, f'_print_{const}', _print_known_const)
445
+
446
+
447
+ _cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()}
448
+ _cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()}
449
+
450
+ class CuPyPrinter(NumPyPrinter):
451
+ """
452
+ CuPy printer which handles vectorized piecewise functions,
453
+ logical operators, etc.
454
+ """
455
+
456
+ _module = 'cupy'
457
+ _kf = _cupy_known_functions
458
+ _kc = _cupy_known_constants
459
+
460
+ def __init__(self, settings=None):
461
+ super().__init__(settings=settings)
462
+
463
+ for func in _cupy_known_functions:
464
+ setattr(CuPyPrinter, f'_print_{func}', _print_known_func)
465
+
466
+ for const in _cupy_known_constants:
467
+ setattr(CuPyPrinter, f'_print_{const}', _print_known_const)
468
+
469
+
470
+ _jax_known_functions = {k: 'jax.numpy.' + v for k, v in _known_functions_numpy.items()}
471
+ _jax_known_constants = {k: 'jax.numpy.' + v for k, v in _known_constants_numpy.items()}
472
+
473
+ class JaxPrinter(NumPyPrinter):
474
+ """
475
+ JAX printer which handles vectorized piecewise functions,
476
+ logical operators, etc.
477
+ """
478
+ _module = "jax.numpy"
479
+
480
+ _kf = _jax_known_functions
481
+ _kc = _jax_known_constants
482
+
483
+ def __init__(self, settings=None):
484
+ super().__init__(settings=settings)
485
+
486
+ # These need specific override to allow for the lack of "jax.numpy.reduce"
487
+ def _print_And(self, expr):
488
+ "Logical And printer"
489
+ return "{}({}.asarray([{}]), axis=0)".format(
490
+ self._module_format(self._module + ".all"),
491
+ self._module_format(self._module),
492
+ ",".join(self._print(i) for i in expr.args),
493
+ )
494
+
495
+ def _print_Or(self, expr):
496
+ "Logical Or printer"
497
+ return "{}({}.asarray([{}]), axis=0)".format(
498
+ self._module_format(self._module + ".any"),
499
+ self._module_format(self._module),
500
+ ",".join(self._print(i) for i in expr.args),
501
+ )
502
+
503
+ for func in _jax_known_functions:
504
+ setattr(JaxPrinter, f'_print_{func}', _print_known_func)
505
+
506
+ for const in _jax_known_constants:
507
+ setattr(JaxPrinter, f'_print_{const}', _print_known_const)
env-llmeval/lib/python3.10/site-packages/sympy/printing/octave.py ADDED
@@ -0,0 +1,719 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Octave (and Matlab) code printer
3
+
4
+ The `OctaveCodePrinter` converts SymPy expressions into Octave expressions.
5
+ It uses a subset of the Octave language for Matlab compatibility.
6
+
7
+ A complete code generator, which uses `octave_code` extensively, can be found
8
+ in `sympy.utilities.codegen`. The `codegen` module can be used to generate
9
+ complete source code files.
10
+
11
+ """
12
+
13
+ from __future__ import annotations
14
+ from typing import Any
15
+
16
+ from sympy.core import Mul, Pow, S, Rational
17
+ from sympy.core.mul import _keep_coeff
18
+ from sympy.core.numbers import equal_valued
19
+ from sympy.printing.codeprinter import CodePrinter
20
+ from sympy.printing.precedence import precedence, PRECEDENCE
21
+ from re import search
22
+
23
+ # List of known functions. First, those that have the same name in
24
+ # SymPy and Octave. This is almost certainly incomplete!
25
+ known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
26
+ "asin", "acos", "acot", "atan", "atan2", "asec", "acsc",
27
+ "sinh", "cosh", "tanh", "coth", "csch", "sech",
28
+ "asinh", "acosh", "atanh", "acoth", "asech", "acsch",
29
+ "erfc", "erfi", "erf", "erfinv", "erfcinv",
30
+ "besseli", "besselj", "besselk", "bessely",
31
+ "bernoulli", "beta", "euler", "exp", "factorial", "floor",
32
+ "fresnelc", "fresnels", "gamma", "harmonic", "log",
33
+ "polylog", "sign", "zeta", "legendre"]
34
+
35
+ # These functions have different names ("SymPy": "Octave"), more
36
+ # generally a mapping to (argument_conditions, octave_function).
37
+ known_fcns_src2 = {
38
+ "Abs": "abs",
39
+ "arg": "angle", # arg/angle ok in Octave but only angle in Matlab
40
+ "binomial": "bincoeff",
41
+ "ceiling": "ceil",
42
+ "chebyshevu": "chebyshevU",
43
+ "chebyshevt": "chebyshevT",
44
+ "Chi": "coshint",
45
+ "Ci": "cosint",
46
+ "conjugate": "conj",
47
+ "DiracDelta": "dirac",
48
+ "Heaviside": "heaviside",
49
+ "im": "imag",
50
+ "laguerre": "laguerreL",
51
+ "LambertW": "lambertw",
52
+ "li": "logint",
53
+ "loggamma": "gammaln",
54
+ "Max": "max",
55
+ "Min": "min",
56
+ "Mod": "mod",
57
+ "polygamma": "psi",
58
+ "re": "real",
59
+ "RisingFactorial": "pochhammer",
60
+ "Shi": "sinhint",
61
+ "Si": "sinint",
62
+ }
63
+
64
+
65
+ class OctaveCodePrinter(CodePrinter):
66
+ """
67
+ A printer to convert expressions to strings of Octave/Matlab code.
68
+ """
69
+ printmethod = "_octave"
70
+ language = "Octave"
71
+
72
+ _operators = {
73
+ 'and': '&',
74
+ 'or': '|',
75
+ 'not': '~',
76
+ }
77
+
78
+ _default_settings: dict[str, Any] = {
79
+ 'order': None,
80
+ 'full_prec': 'auto',
81
+ 'precision': 17,
82
+ 'user_functions': {},
83
+ 'human': True,
84
+ 'allow_unknown_functions': False,
85
+ 'contract': True,
86
+ 'inline': True,
87
+ }
88
+ # Note: contract is for expressing tensors as loops (if True), or just
89
+ # assignment (if False). FIXME: this should be looked a more carefully
90
+ # for Octave.
91
+
92
+
93
+ def __init__(self, settings={}):
94
+ super().__init__(settings)
95
+ self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
96
+ self.known_functions.update(dict(known_fcns_src2))
97
+ userfuncs = settings.get('user_functions', {})
98
+ self.known_functions.update(userfuncs)
99
+
100
+
101
+ def _rate_index_position(self, p):
102
+ return p*5
103
+
104
+
105
+ def _get_statement(self, codestring):
106
+ return "%s;" % codestring
107
+
108
+
109
+ def _get_comment(self, text):
110
+ return "% {}".format(text)
111
+
112
+
113
+ def _declare_number_const(self, name, value):
114
+ return "{} = {};".format(name, value)
115
+
116
+
117
+ def _format_code(self, lines):
118
+ return self.indent_code(lines)
119
+
120
+
121
+ def _traverse_matrix_indices(self, mat):
122
+ # Octave uses Fortran order (column-major)
123
+ rows, cols = mat.shape
124
+ return ((i, j) for j in range(cols) for i in range(rows))
125
+
126
+
127
+ def _get_loop_opening_ending(self, indices):
128
+ open_lines = []
129
+ close_lines = []
130
+ for i in indices:
131
+ # Octave arrays start at 1 and end at dimension
132
+ var, start, stop = map(self._print,
133
+ [i.label, i.lower + 1, i.upper + 1])
134
+ open_lines.append("for %s = %s:%s" % (var, start, stop))
135
+ close_lines.append("end")
136
+ return open_lines, close_lines
137
+
138
+
139
+ def _print_Mul(self, expr):
140
+ # print complex numbers nicely in Octave
141
+ if (expr.is_number and expr.is_imaginary and
142
+ (S.ImaginaryUnit*expr).is_Integer):
143
+ return "%si" % self._print(-S.ImaginaryUnit*expr)
144
+
145
+ # cribbed from str.py
146
+ prec = precedence(expr)
147
+
148
+ c, e = expr.as_coeff_Mul()
149
+ if c < 0:
150
+ expr = _keep_coeff(-c, e)
151
+ sign = "-"
152
+ else:
153
+ sign = ""
154
+
155
+ a = [] # items in the numerator
156
+ b = [] # items that are in the denominator (if any)
157
+
158
+ pow_paren = [] # Will collect all pow with more than one base element and exp = -1
159
+
160
+ if self.order not in ('old', 'none'):
161
+ args = expr.as_ordered_factors()
162
+ else:
163
+ # use make_args in case expr was something like -x -> x
164
+ args = Mul.make_args(expr)
165
+
166
+ # Gather args for numerator/denominator
167
+ for item in args:
168
+ if (item.is_commutative and item.is_Pow and item.exp.is_Rational
169
+ and item.exp.is_negative):
170
+ if item.exp != -1:
171
+ b.append(Pow(item.base, -item.exp, evaluate=False))
172
+ else:
173
+ if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
174
+ pow_paren.append(item)
175
+ b.append(Pow(item.base, -item.exp))
176
+ elif item.is_Rational and item is not S.Infinity:
177
+ if item.p != 1:
178
+ a.append(Rational(item.p))
179
+ if item.q != 1:
180
+ b.append(Rational(item.q))
181
+ else:
182
+ a.append(item)
183
+
184
+ a = a or [S.One]
185
+
186
+ a_str = [self.parenthesize(x, prec) for x in a]
187
+ b_str = [self.parenthesize(x, prec) for x in b]
188
+
189
+ # To parenthesize Pow with exp = -1 and having more than one Symbol
190
+ for item in pow_paren:
191
+ if item.base in b:
192
+ b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
193
+
194
+ # from here it differs from str.py to deal with "*" and ".*"
195
+ def multjoin(a, a_str):
196
+ # here we probably are assuming the constants will come first
197
+ r = a_str[0]
198
+ for i in range(1, len(a)):
199
+ mulsym = '*' if a[i-1].is_number else '.*'
200
+ r = r + mulsym + a_str[i]
201
+ return r
202
+
203
+ if not b:
204
+ return sign + multjoin(a, a_str)
205
+ elif len(b) == 1:
206
+ divsym = '/' if b[0].is_number else './'
207
+ return sign + multjoin(a, a_str) + divsym + b_str[0]
208
+ else:
209
+ divsym = '/' if all(bi.is_number for bi in b) else './'
210
+ return (sign + multjoin(a, a_str) +
211
+ divsym + "(%s)" % multjoin(b, b_str))
212
+
213
+ def _print_Relational(self, expr):
214
+ lhs_code = self._print(expr.lhs)
215
+ rhs_code = self._print(expr.rhs)
216
+ op = expr.rel_op
217
+ return "{} {} {}".format(lhs_code, op, rhs_code)
218
+
219
+ def _print_Pow(self, expr):
220
+ powsymbol = '^' if all(x.is_number for x in expr.args) else '.^'
221
+
222
+ PREC = precedence(expr)
223
+
224
+ if equal_valued(expr.exp, 0.5):
225
+ return "sqrt(%s)" % self._print(expr.base)
226
+
227
+ if expr.is_commutative:
228
+ if equal_valued(expr.exp, -0.5):
229
+ sym = '/' if expr.base.is_number else './'
230
+ return "1" + sym + "sqrt(%s)" % self._print(expr.base)
231
+ if equal_valued(expr.exp, -1):
232
+ sym = '/' if expr.base.is_number else './'
233
+ return "1" + sym + "%s" % self.parenthesize(expr.base, PREC)
234
+
235
+ return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol,
236
+ self.parenthesize(expr.exp, PREC))
237
+
238
+
239
+ def _print_MatPow(self, expr):
240
+ PREC = precedence(expr)
241
+ return '%s^%s' % (self.parenthesize(expr.base, PREC),
242
+ self.parenthesize(expr.exp, PREC))
243
+
244
+ def _print_MatrixSolve(self, expr):
245
+ PREC = precedence(expr)
246
+ return "%s \\ %s" % (self.parenthesize(expr.matrix, PREC),
247
+ self.parenthesize(expr.vector, PREC))
248
+
249
+ def _print_Pi(self, expr):
250
+ return 'pi'
251
+
252
+
253
+ def _print_ImaginaryUnit(self, expr):
254
+ return "1i"
255
+
256
+
257
+ def _print_Exp1(self, expr):
258
+ return "exp(1)"
259
+
260
+
261
+ def _print_GoldenRatio(self, expr):
262
+ # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)?
263
+ #return self._print((1+sqrt(S(5)))/2)
264
+ return "(1+sqrt(5))/2"
265
+
266
+
267
+ def _print_Assignment(self, expr):
268
+ from sympy.codegen.ast import Assignment
269
+ from sympy.functions.elementary.piecewise import Piecewise
270
+ from sympy.tensor.indexed import IndexedBase
271
+ # Copied from codeprinter, but remove special MatrixSymbol treatment
272
+ lhs = expr.lhs
273
+ rhs = expr.rhs
274
+ # We special case assignments that take multiple lines
275
+ if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
276
+ # Here we modify Piecewise so each expression is now
277
+ # an Assignment, and then continue on the print.
278
+ expressions = []
279
+ conditions = []
280
+ for (e, c) in rhs.args:
281
+ expressions.append(Assignment(lhs, e))
282
+ conditions.append(c)
283
+ temp = Piecewise(*zip(expressions, conditions))
284
+ return self._print(temp)
285
+ if self._settings["contract"] and (lhs.has(IndexedBase) or
286
+ rhs.has(IndexedBase)):
287
+ # Here we check if there is looping to be done, and if so
288
+ # print the required loops.
289
+ return self._doprint_loops(rhs, lhs)
290
+ else:
291
+ lhs_code = self._print(lhs)
292
+ rhs_code = self._print(rhs)
293
+ return self._get_statement("%s = %s" % (lhs_code, rhs_code))
294
+
295
+
296
+ def _print_Infinity(self, expr):
297
+ return 'inf'
298
+
299
+
300
+ def _print_NegativeInfinity(self, expr):
301
+ return '-inf'
302
+
303
+
304
+ def _print_NaN(self, expr):
305
+ return 'NaN'
306
+
307
+
308
+ def _print_list(self, expr):
309
+ return '{' + ', '.join(self._print(a) for a in expr) + '}'
310
+ _print_tuple = _print_list
311
+ _print_Tuple = _print_list
312
+ _print_List = _print_list
313
+
314
+
315
+ def _print_BooleanTrue(self, expr):
316
+ return "true"
317
+
318
+
319
+ def _print_BooleanFalse(self, expr):
320
+ return "false"
321
+
322
+
323
+ def _print_bool(self, expr):
324
+ return str(expr).lower()
325
+
326
+
327
+ # Could generate quadrature code for definite Integrals?
328
+ #_print_Integral = _print_not_supported
329
+
330
+
331
+ def _print_MatrixBase(self, A):
332
+ # Handle zero dimensions:
333
+ if (A.rows, A.cols) == (0, 0):
334
+ return '[]'
335
+ elif S.Zero in A.shape:
336
+ return 'zeros(%s, %s)' % (A.rows, A.cols)
337
+ elif (A.rows, A.cols) == (1, 1):
338
+ # Octave does not distinguish between scalars and 1x1 matrices
339
+ return self._print(A[0, 0])
340
+ return "[%s]" % "; ".join(" ".join([self._print(a) for a in A[r, :]])
341
+ for r in range(A.rows))
342
+
343
+
344
+ def _print_SparseRepMatrix(self, A):
345
+ from sympy.matrices import Matrix
346
+ L = A.col_list();
347
+ # make row vectors of the indices and entries
348
+ I = Matrix([[k[0] + 1 for k in L]])
349
+ J = Matrix([[k[1] + 1 for k in L]])
350
+ AIJ = Matrix([[k[2] for k in L]])
351
+ return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
352
+ self._print(AIJ), A.rows, A.cols)
353
+
354
+
355
+ def _print_MatrixElement(self, expr):
356
+ return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
357
+ + '(%s, %s)' % (expr.i + 1, expr.j + 1)
358
+
359
+
360
+ def _print_MatrixSlice(self, expr):
361
+ def strslice(x, lim):
362
+ l = x[0] + 1
363
+ h = x[1]
364
+ step = x[2]
365
+ lstr = self._print(l)
366
+ hstr = 'end' if h == lim else self._print(h)
367
+ if step == 1:
368
+ if l == 1 and h == lim:
369
+ return ':'
370
+ if l == h:
371
+ return lstr
372
+ else:
373
+ return lstr + ':' + hstr
374
+ else:
375
+ return ':'.join((lstr, self._print(step), hstr))
376
+ return (self._print(expr.parent) + '(' +
377
+ strslice(expr.rowslice, expr.parent.shape[0]) + ', ' +
378
+ strslice(expr.colslice, expr.parent.shape[1]) + ')')
379
+
380
+
381
+ def _print_Indexed(self, expr):
382
+ inds = [ self._print(i) for i in expr.indices ]
383
+ return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds))
384
+
385
+
386
+ def _print_Idx(self, expr):
387
+ return self._print(expr.label)
388
+
389
+
390
+ def _print_KroneckerDelta(self, expr):
391
+ prec = PRECEDENCE["Pow"]
392
+ return "double(%s == %s)" % tuple(self.parenthesize(x, prec)
393
+ for x in expr.args)
394
+
395
+ def _print_HadamardProduct(self, expr):
396
+ return '.*'.join([self.parenthesize(arg, precedence(expr))
397
+ for arg in expr.args])
398
+
399
+ def _print_HadamardPower(self, expr):
400
+ PREC = precedence(expr)
401
+ return '.**'.join([
402
+ self.parenthesize(expr.base, PREC),
403
+ self.parenthesize(expr.exp, PREC)
404
+ ])
405
+
406
+ def _print_Identity(self, expr):
407
+ shape = expr.shape
408
+ if len(shape) == 2 and shape[0] == shape[1]:
409
+ shape = [shape[0]]
410
+ s = ", ".join(self._print(n) for n in shape)
411
+ return "eye(" + s + ")"
412
+
413
+ def _print_lowergamma(self, expr):
414
+ # Octave implements regularized incomplete gamma function
415
+ return "(gammainc({1}, {0}).*gamma({0}))".format(
416
+ self._print(expr.args[0]), self._print(expr.args[1]))
417
+
418
+
419
+ def _print_uppergamma(self, expr):
420
+ return "(gammainc({1}, {0}, 'upper').*gamma({0}))".format(
421
+ self._print(expr.args[0]), self._print(expr.args[1]))
422
+
423
+
424
+ def _print_sinc(self, expr):
425
+ #Note: Divide by pi because Octave implements normalized sinc function.
426
+ return "sinc(%s)" % self._print(expr.args[0]/S.Pi)
427
+
428
+
429
+ def _print_hankel1(self, expr):
430
+ return "besselh(%s, 1, %s)" % (self._print(expr.order),
431
+ self._print(expr.argument))
432
+
433
+
434
+ def _print_hankel2(self, expr):
435
+ return "besselh(%s, 2, %s)" % (self._print(expr.order),
436
+ self._print(expr.argument))
437
+
438
+
439
+ # Note: as of 2015, Octave doesn't have spherical Bessel functions
440
+ def _print_jn(self, expr):
441
+ from sympy.functions import sqrt, besselj
442
+ x = expr.argument
443
+ expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
444
+ return self._print(expr2)
445
+
446
+
447
+ def _print_yn(self, expr):
448
+ from sympy.functions import sqrt, bessely
449
+ x = expr.argument
450
+ expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
451
+ return self._print(expr2)
452
+
453
+
454
+ def _print_airyai(self, expr):
455
+ return "airy(0, %s)" % self._print(expr.args[0])
456
+
457
+
458
+ def _print_airyaiprime(self, expr):
459
+ return "airy(1, %s)" % self._print(expr.args[0])
460
+
461
+
462
+ def _print_airybi(self, expr):
463
+ return "airy(2, %s)" % self._print(expr.args[0])
464
+
465
+
466
+ def _print_airybiprime(self, expr):
467
+ return "airy(3, %s)" % self._print(expr.args[0])
468
+
469
+
470
+ def _print_expint(self, expr):
471
+ mu, x = expr.args
472
+ if mu != 1:
473
+ return self._print_not_supported(expr)
474
+ return "expint(%s)" % self._print(x)
475
+
476
+
477
+ def _one_or_two_reversed_args(self, expr):
478
+ assert len(expr.args) <= 2
479
+ return '{name}({args})'.format(
480
+ name=self.known_functions[expr.__class__.__name__],
481
+ args=", ".join([self._print(x) for x in reversed(expr.args)])
482
+ )
483
+
484
+
485
+ _print_DiracDelta = _print_LambertW = _one_or_two_reversed_args
486
+
487
+
488
+ def _nested_binary_math_func(self, expr):
489
+ return '{name}({arg1}, {arg2})'.format(
490
+ name=self.known_functions[expr.__class__.__name__],
491
+ arg1=self._print(expr.args[0]),
492
+ arg2=self._print(expr.func(*expr.args[1:]))
493
+ )
494
+
495
+ _print_Max = _print_Min = _nested_binary_math_func
496
+
497
+
498
+ def _print_Piecewise(self, expr):
499
+ if expr.args[-1].cond != True:
500
+ # We need the last conditional to be a True, otherwise the resulting
501
+ # function may not return a result.
502
+ raise ValueError("All Piecewise expressions must contain an "
503
+ "(expr, True) statement to be used as a default "
504
+ "condition. Without one, the generated "
505
+ "expression may not evaluate to anything under "
506
+ "some condition.")
507
+ lines = []
508
+ if self._settings["inline"]:
509
+ # Express each (cond, expr) pair in a nested Horner form:
510
+ # (condition) .* (expr) + (not cond) .* (<others>)
511
+ # Expressions that result in multiple statements won't work here.
512
+ ecpairs = ["({0}).*({1}) + (~({0})).*(".format
513
+ (self._print(c), self._print(e))
514
+ for e, c in expr.args[:-1]]
515
+ elast = "%s" % self._print(expr.args[-1].expr)
516
+ pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs)
517
+ # Note: current need these outer brackets for 2*pw. Would be
518
+ # nicer to teach parenthesize() to do this for us when needed!
519
+ return "(" + pw + ")"
520
+ else:
521
+ for i, (e, c) in enumerate(expr.args):
522
+ if i == 0:
523
+ lines.append("if (%s)" % self._print(c))
524
+ elif i == len(expr.args) - 1 and c == True:
525
+ lines.append("else")
526
+ else:
527
+ lines.append("elseif (%s)" % self._print(c))
528
+ code0 = self._print(e)
529
+ lines.append(code0)
530
+ if i == len(expr.args) - 1:
531
+ lines.append("end")
532
+ return "\n".join(lines)
533
+
534
+
535
+ def _print_zeta(self, expr):
536
+ if len(expr.args) == 1:
537
+ return "zeta(%s)" % self._print(expr.args[0])
538
+ else:
539
+ # Matlab two argument zeta is not equivalent to SymPy's
540
+ return self._print_not_supported(expr)
541
+
542
+
543
+ def indent_code(self, code):
544
+ """Accepts a string of code or a list of code lines"""
545
+
546
+ # code mostly copied from ccode
547
+ if isinstance(code, str):
548
+ code_lines = self.indent_code(code.splitlines(True))
549
+ return ''.join(code_lines)
550
+
551
+ tab = " "
552
+ inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
553
+ dec_regex = ('^end$', '^elseif ', '^else$')
554
+
555
+ # pre-strip left-space from the code
556
+ code = [ line.lstrip(' \t') for line in code ]
557
+
558
+ increase = [ int(any(search(re, line) for re in inc_regex))
559
+ for line in code ]
560
+ decrease = [ int(any(search(re, line) for re in dec_regex))
561
+ for line in code ]
562
+
563
+ pretty = []
564
+ level = 0
565
+ for n, line in enumerate(code):
566
+ if line in ('', '\n'):
567
+ pretty.append(line)
568
+ continue
569
+ level -= decrease[n]
570
+ pretty.append("%s%s" % (tab*level, line))
571
+ level += increase[n]
572
+ return pretty
573
+
574
+
575
+ def octave_code(expr, assign_to=None, **settings):
576
+ r"""Converts `expr` to a string of Octave (or Matlab) code.
577
+
578
+ The string uses a subset of the Octave language for Matlab compatibility.
579
+
580
+ Parameters
581
+ ==========
582
+
583
+ expr : Expr
584
+ A SymPy expression to be converted.
585
+ assign_to : optional
586
+ When given, the argument is used as the name of the variable to which
587
+ the expression is assigned. Can be a string, ``Symbol``,
588
+ ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
589
+ expressions that generate multi-line statements.
590
+ precision : integer, optional
591
+ The precision for numbers such as pi [default=16].
592
+ user_functions : dict, optional
593
+ A dictionary where keys are ``FunctionClass`` instances and values are
594
+ their string representations. Alternatively, the dictionary value can
595
+ be a list of tuples i.e. [(argument_test, cfunction_string)]. See
596
+ below for examples.
597
+ human : bool, optional
598
+ If True, the result is a single string that may contain some constant
599
+ declarations for the number symbols. If False, the same information is
600
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
601
+ code_text). [default=True].
602
+ contract: bool, optional
603
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
604
+ rules and the corresponding nested loops over indices are generated.
605
+ Setting contract=False will not generate loops, instead the user is
606
+ responsible to provide values for the indices in the code.
607
+ [default=True].
608
+ inline: bool, optional
609
+ If True, we try to create single-statement code instead of multiple
610
+ statements. [default=True].
611
+
612
+ Examples
613
+ ========
614
+
615
+ >>> from sympy import octave_code, symbols, sin, pi
616
+ >>> x = symbols('x')
617
+ >>> octave_code(sin(x).series(x).removeO())
618
+ 'x.^5/120 - x.^3/6 + x'
619
+
620
+ >>> from sympy import Rational, ceiling
621
+ >>> x, y, tau = symbols("x, y, tau")
622
+ >>> octave_code((2*tau)**Rational(7, 2))
623
+ '8*sqrt(2)*tau.^(7/2)'
624
+
625
+ Note that element-wise (Hadamard) operations are used by default between
626
+ symbols. This is because its very common in Octave to write "vectorized"
627
+ code. It is harmless if the values are scalars.
628
+
629
+ >>> octave_code(sin(pi*x*y), assign_to="s")
630
+ 's = sin(pi*x.*y);'
631
+
632
+ If you need a matrix product "*" or matrix power "^", you can specify the
633
+ symbol as a ``MatrixSymbol``.
634
+
635
+ >>> from sympy import Symbol, MatrixSymbol
636
+ >>> n = Symbol('n', integer=True, positive=True)
637
+ >>> A = MatrixSymbol('A', n, n)
638
+ >>> octave_code(3*pi*A**3)
639
+ '(3*pi)*A^3'
640
+
641
+ This class uses several rules to decide which symbol to use a product.
642
+ Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
643
+ A HadamardProduct can be used to specify componentwise multiplication ".*"
644
+ of two MatrixSymbols. There is currently there is no easy way to specify
645
+ scalar symbols, so sometimes the code might have some minor cosmetic
646
+ issues. For example, suppose x and y are scalars and A is a Matrix, then
647
+ while a human programmer might write "(x^2*y)*A^3", we generate:
648
+
649
+ >>> octave_code(x**2*y*A**3)
650
+ '(x.^2.*y)*A^3'
651
+
652
+ Matrices are supported using Octave inline notation. When using
653
+ ``assign_to`` with matrices, the name can be specified either as a string
654
+ or as a ``MatrixSymbol``. The dimensions must align in the latter case.
655
+
656
+ >>> from sympy import Matrix, MatrixSymbol
657
+ >>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
658
+ >>> octave_code(mat, assign_to='A')
659
+ 'A = [x.^2 sin(x) ceil(x)];'
660
+
661
+ ``Piecewise`` expressions are implemented with logical masking by default.
662
+ Alternatively, you can pass "inline=False" to use if-else conditionals.
663
+ Note that if the ``Piecewise`` lacks a default term, represented by
664
+ ``(expr, True)`` then an error will be thrown. This is to prevent
665
+ generating an expression that may not evaluate to anything.
666
+
667
+ >>> from sympy import Piecewise
668
+ >>> pw = Piecewise((x + 1, x > 0), (x, True))
669
+ >>> octave_code(pw, assign_to=tau)
670
+ 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));'
671
+
672
+ Note that any expression that can be generated normally can also exist
673
+ inside a Matrix:
674
+
675
+ >>> mat = Matrix([[x**2, pw, sin(x)]])
676
+ >>> octave_code(mat, assign_to='A')
677
+ 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];'
678
+
679
+ Custom printing can be defined for certain types by passing a dictionary of
680
+ "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
681
+ dictionary value can be a list of tuples i.e., [(argument_test,
682
+ cfunction_string)]. This can be used to call a custom Octave function.
683
+
684
+ >>> from sympy import Function
685
+ >>> f = Function('f')
686
+ >>> g = Function('g')
687
+ >>> custom_functions = {
688
+ ... "f": "existing_octave_fcn",
689
+ ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
690
+ ... (lambda x: not x.is_Matrix, "my_fcn")]
691
+ ... }
692
+ >>> mat = Matrix([[1, x]])
693
+ >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
694
+ 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
695
+
696
+ Support for loops is provided through ``Indexed`` types. With
697
+ ``contract=True`` these expressions will be turned into loops, whereas
698
+ ``contract=False`` will just print the assignment expression that should be
699
+ looped over:
700
+
701
+ >>> from sympy import Eq, IndexedBase, Idx
702
+ >>> len_y = 5
703
+ >>> y = IndexedBase('y', shape=(len_y,))
704
+ >>> t = IndexedBase('t', shape=(len_y,))
705
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
706
+ >>> i = Idx('i', len_y-1)
707
+ >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
708
+ >>> octave_code(e.rhs, assign_to=e.lhs, contract=False)
709
+ 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));'
710
+ """
711
+ return OctaveCodePrinter(settings).doprint(expr, assign_to)
712
+
713
+
714
+ def print_octave_code(expr, **settings):
715
+ """Prints the Octave (or Matlab) representation of the given expression.
716
+
717
+ See `octave_code` for the meaning of the optional arguments.
718
+ """
719
+ print(octave_code(expr, **settings))
env-llmeval/lib/python3.10/site-packages/sympy/printing/preview.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from os.path import join
3
+ import shutil
4
+ import tempfile
5
+
6
+ try:
7
+ from subprocess import STDOUT, CalledProcessError, check_output
8
+ except ImportError:
9
+ pass
10
+
11
+ from sympy.utilities.decorator import doctest_depends_on
12
+ from sympy.utilities.misc import debug
13
+ from .latex import latex
14
+
15
+ __doctest_requires__ = {('preview',): ['pyglet']}
16
+
17
+
18
+ def _check_output_no_window(*args, **kwargs):
19
+ # Avoid showing a cmd.exe window when running this
20
+ # on Windows
21
+ if os.name == 'nt':
22
+ creation_flag = 0x08000000 # CREATE_NO_WINDOW
23
+ else:
24
+ creation_flag = 0 # Default value
25
+ return check_output(*args, creationflags=creation_flag, **kwargs)
26
+
27
+
28
+ def system_default_viewer(fname, fmt):
29
+ """ Open fname with the default system viewer.
30
+
31
+ In practice, it is impossible for python to know when the system viewer is
32
+ done. For this reason, we ensure the passed file will not be deleted under
33
+ it, and this function does not attempt to block.
34
+ """
35
+ # copy to a new temporary file that will not be deleted
36
+ with tempfile.NamedTemporaryFile(prefix='sympy-preview-',
37
+ suffix=os.path.splitext(fname)[1],
38
+ delete=False) as temp_f:
39
+ with open(fname, 'rb') as f:
40
+ shutil.copyfileobj(f, temp_f)
41
+
42
+ import platform
43
+ if platform.system() == 'Darwin':
44
+ import subprocess
45
+ subprocess.call(('open', temp_f.name))
46
+ elif platform.system() == 'Windows':
47
+ os.startfile(temp_f.name)
48
+ else:
49
+ import subprocess
50
+ subprocess.call(('xdg-open', temp_f.name))
51
+
52
+
53
+ def pyglet_viewer(fname, fmt):
54
+ try:
55
+ from pyglet import window, image, gl
56
+ from pyglet.window import key
57
+ from pyglet.image.codecs import ImageDecodeException
58
+ except ImportError:
59
+ raise ImportError("pyglet is required for preview.\n visit https://pyglet.org/")
60
+
61
+ try:
62
+ img = image.load(fname)
63
+ except ImageDecodeException:
64
+ raise ValueError("pyglet preview does not work for '{}' files.".format(fmt))
65
+
66
+ offset = 25
67
+
68
+ config = gl.Config(double_buffer=False)
69
+ win = window.Window(
70
+ width=img.width + 2*offset,
71
+ height=img.height + 2*offset,
72
+ caption="SymPy",
73
+ resizable=False,
74
+ config=config
75
+ )
76
+
77
+ win.set_vsync(False)
78
+
79
+ try:
80
+ def on_close():
81
+ win.has_exit = True
82
+
83
+ win.on_close = on_close
84
+
85
+ def on_key_press(symbol, modifiers):
86
+ if symbol in [key.Q, key.ESCAPE]:
87
+ on_close()
88
+
89
+ win.on_key_press = on_key_press
90
+
91
+ def on_expose():
92
+ gl.glClearColor(1.0, 1.0, 1.0, 1.0)
93
+ gl.glClear(gl.GL_COLOR_BUFFER_BIT)
94
+
95
+ img.blit(
96
+ (win.width - img.width) / 2,
97
+ (win.height - img.height) / 2
98
+ )
99
+
100
+ win.on_expose = on_expose
101
+
102
+ while not win.has_exit:
103
+ win.dispatch_events()
104
+ win.flip()
105
+ except KeyboardInterrupt:
106
+ pass
107
+
108
+ win.close()
109
+
110
+
111
+ def _get_latex_main(expr, *, preamble=None, packages=(), extra_preamble=None,
112
+ euler=True, fontsize=None, **latex_settings):
113
+ """
114
+ Generate string of a LaTeX document rendering ``expr``.
115
+ """
116
+ if preamble is None:
117
+ actual_packages = packages + ("amsmath", "amsfonts")
118
+ if euler:
119
+ actual_packages += ("euler",)
120
+ package_includes = "\n" + "\n".join(["\\usepackage{%s}" % p
121
+ for p in actual_packages])
122
+ if extra_preamble:
123
+ package_includes += extra_preamble
124
+
125
+ if not fontsize:
126
+ fontsize = "12pt"
127
+ elif isinstance(fontsize, int):
128
+ fontsize = "{}pt".format(fontsize)
129
+ preamble = r"""\documentclass[varwidth,%s]{standalone}
130
+ %s
131
+
132
+ \begin{document}
133
+ """ % (fontsize, package_includes)
134
+ else:
135
+ if packages or extra_preamble:
136
+ raise ValueError("The \"packages\" or \"extra_preamble\" keywords"
137
+ "must not be set if a "
138
+ "custom LaTeX preamble was specified")
139
+
140
+ if isinstance(expr, str):
141
+ latex_string = expr
142
+ else:
143
+ latex_string = ('$\\displaystyle ' +
144
+ latex(expr, mode='plain', **latex_settings) +
145
+ '$')
146
+
147
+ return preamble + '\n' + latex_string + '\n\n' + r"\end{document}"
148
+
149
+
150
+ @doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',),
151
+ disable_viewers=('evince', 'gimp', 'superior-dvi-viewer'))
152
+ def preview(expr, output='png', viewer=None, euler=True, packages=(),
153
+ filename=None, outputbuffer=None, preamble=None, dvioptions=None,
154
+ outputTexFile=None, extra_preamble=None, fontsize=None,
155
+ **latex_settings):
156
+ r"""
157
+ View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.
158
+
159
+ If the expr argument is an expression, it will be exported to LaTeX and
160
+ then compiled using the available TeX distribution. The first argument,
161
+ 'expr', may also be a LaTeX string. The function will then run the
162
+ appropriate viewer for the given output format or use the user defined
163
+ one. By default png output is generated.
164
+
165
+ By default pretty Euler fonts are used for typesetting (they were used to
166
+ typeset the well known "Concrete Mathematics" book). For that to work, you
167
+ need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the
168
+ texlive-fonts-extra package). If you prefer default AMS fonts or your
169
+ system lacks 'eulervm' LaTeX package then unset the 'euler' keyword
170
+ argument.
171
+
172
+ To use viewer auto-detection, lets say for 'png' output, issue
173
+
174
+ >>> from sympy import symbols, preview, Symbol
175
+ >>> x, y = symbols("x,y")
176
+
177
+ >>> preview(x + y, output='png')
178
+
179
+ This will choose 'pyglet' by default. To select a different one, do
180
+
181
+ >>> preview(x + y, output='png', viewer='gimp')
182
+
183
+ The 'png' format is considered special. For all other formats the rules
184
+ are slightly different. As an example we will take 'dvi' output format. If
185
+ you would run
186
+
187
+ >>> preview(x + y, output='dvi')
188
+
189
+ then 'view' will look for available 'dvi' viewers on your system
190
+ (predefined in the function, so it will try evince, first, then kdvi and
191
+ xdvi). If nothing is found, it will fall back to using a system file
192
+ association (via ``open`` and ``xdg-open``). To always use your system file
193
+ association without searching for the above readers, use
194
+
195
+ >>> from sympy.printing.preview import system_default_viewer
196
+ >>> preview(x + y, output='dvi', viewer=system_default_viewer)
197
+
198
+ If this still does not find the viewer you want, it can be set explicitly.
199
+
200
+ >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')
201
+
202
+ This will skip auto-detection and will run user specified
203
+ 'superior-dvi-viewer'. If ``view`` fails to find it on your system it will
204
+ gracefully raise an exception.
205
+
206
+ You may also enter ``'file'`` for the viewer argument. Doing so will cause
207
+ this function to return a file object in read-only mode, if ``filename``
208
+ is unset. However, if it was set, then 'preview' writes the generated
209
+ file to this filename instead.
210
+
211
+ There is also support for writing to a ``io.BytesIO`` like object, which
212
+ needs to be passed to the ``outputbuffer`` argument.
213
+
214
+ >>> from io import BytesIO
215
+ >>> obj = BytesIO()
216
+ >>> preview(x + y, output='png', viewer='BytesIO',
217
+ ... outputbuffer=obj)
218
+
219
+ The LaTeX preamble can be customized by setting the 'preamble' keyword
220
+ argument. This can be used, e.g., to set a different font size, use a
221
+ custom documentclass or import certain set of LaTeX packages.
222
+
223
+ >>> preamble = "\\documentclass[10pt]{article}\n" \
224
+ ... "\\usepackage{amsmath,amsfonts}\\begin{document}"
225
+ >>> preview(x + y, output='png', preamble=preamble)
226
+
227
+ It is also possible to use the standard preamble and provide additional
228
+ information to the preamble using the ``extra_preamble`` keyword argument.
229
+
230
+ >>> from sympy import sin
231
+ >>> extra_preamble = "\\renewcommand{\\sin}{\\cos}"
232
+ >>> preview(sin(x), output='png', extra_preamble=extra_preamble)
233
+
234
+ If the value of 'output' is different from 'dvi' then command line
235
+ options can be set ('dvioptions' argument) for the execution of the
236
+ 'dvi'+output conversion tool. These options have to be in the form of a
237
+ list of strings (see ``subprocess.Popen``).
238
+
239
+ Additional keyword args will be passed to the :func:`~sympy.printing.latex.latex` call,
240
+ e.g., the ``symbol_names`` flag.
241
+
242
+ >>> phidd = Symbol('phidd')
243
+ >>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'})
244
+
245
+ For post-processing the generated TeX File can be written to a file by
246
+ passing the desired filename to the 'outputTexFile' keyword
247
+ argument. To write the TeX code to a file named
248
+ ``"sample.tex"`` and run the default png viewer to display the resulting
249
+ bitmap, do
250
+
251
+ >>> preview(x + y, outputTexFile="sample.tex")
252
+
253
+
254
+ """
255
+ # pyglet is the default for png
256
+ if viewer is None and output == "png":
257
+ try:
258
+ import pyglet # noqa: F401
259
+ except ImportError:
260
+ pass
261
+ else:
262
+ viewer = pyglet_viewer
263
+
264
+ # look up a known application
265
+ if viewer is None:
266
+ # sorted in order from most pretty to most ugly
267
+ # very discussable, but indeed 'gv' looks awful :)
268
+ candidates = {
269
+ "dvi": [ "evince", "okular", "kdvi", "xdvi" ],
270
+ "ps": [ "evince", "okular", "gsview", "gv" ],
271
+ "pdf": [ "evince", "okular", "kpdf", "acroread", "xpdf", "gv" ],
272
+ }
273
+
274
+ for candidate in candidates.get(output, []):
275
+ path = shutil.which(candidate)
276
+ if path is not None:
277
+ viewer = path
278
+ break
279
+
280
+ # otherwise, use the system default for file association
281
+ if viewer is None:
282
+ viewer = system_default_viewer
283
+
284
+ if viewer == "file":
285
+ if filename is None:
286
+ raise ValueError("filename has to be specified if viewer=\"file\"")
287
+ elif viewer == "BytesIO":
288
+ if outputbuffer is None:
289
+ raise ValueError("outputbuffer has to be a BytesIO "
290
+ "compatible object if viewer=\"BytesIO\"")
291
+ elif not callable(viewer) and not shutil.which(viewer):
292
+ raise OSError("Unrecognized viewer: %s" % viewer)
293
+
294
+ latex_main = _get_latex_main(expr, preamble=preamble, packages=packages,
295
+ euler=euler, extra_preamble=extra_preamble,
296
+ fontsize=fontsize, **latex_settings)
297
+
298
+ debug("Latex code:")
299
+ debug(latex_main)
300
+ with tempfile.TemporaryDirectory() as workdir:
301
+ with open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh:
302
+ fh.write(latex_main)
303
+
304
+ if outputTexFile is not None:
305
+ shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile)
306
+
307
+ if not shutil.which('latex'):
308
+ raise RuntimeError("latex program is not installed")
309
+
310
+ try:
311
+ _check_output_no_window(
312
+ ['latex', '-halt-on-error', '-interaction=nonstopmode',
313
+ 'texput.tex'],
314
+ cwd=workdir,
315
+ stderr=STDOUT)
316
+ except CalledProcessError as e:
317
+ raise RuntimeError(
318
+ "'latex' exited abnormally with the following output:\n%s" %
319
+ e.output)
320
+
321
+ src = "texput.%s" % (output)
322
+
323
+ if output != "dvi":
324
+ # in order of preference
325
+ commandnames = {
326
+ "ps": ["dvips"],
327
+ "pdf": ["dvipdfmx", "dvipdfm", "dvipdf"],
328
+ "png": ["dvipng"],
329
+ "svg": ["dvisvgm"],
330
+ }
331
+ try:
332
+ cmd_variants = commandnames[output]
333
+ except KeyError:
334
+ raise ValueError("Invalid output format: %s" % output) from None
335
+
336
+ # find an appropriate command
337
+ for cmd_variant in cmd_variants:
338
+ cmd_path = shutil.which(cmd_variant)
339
+ if cmd_path:
340
+ cmd = [cmd_path]
341
+ break
342
+ else:
343
+ if len(cmd_variants) > 1:
344
+ raise RuntimeError("None of %s are installed" % ", ".join(cmd_variants))
345
+ else:
346
+ raise RuntimeError("%s is not installed" % cmd_variants[0])
347
+
348
+ defaultoptions = {
349
+ "dvipng": ["-T", "tight", "-z", "9", "--truecolor"],
350
+ "dvisvgm": ["--no-fonts"],
351
+ }
352
+
353
+ commandend = {
354
+ "dvips": ["-o", src, "texput.dvi"],
355
+ "dvipdf": ["texput.dvi", src],
356
+ "dvipdfm": ["-o", src, "texput.dvi"],
357
+ "dvipdfmx": ["-o", src, "texput.dvi"],
358
+ "dvipng": ["-o", src, "texput.dvi"],
359
+ "dvisvgm": ["-o", src, "texput.dvi"],
360
+ }
361
+
362
+ if dvioptions is not None:
363
+ cmd.extend(dvioptions)
364
+ else:
365
+ cmd.extend(defaultoptions.get(cmd_variant, []))
366
+ cmd.extend(commandend[cmd_variant])
367
+
368
+ try:
369
+ _check_output_no_window(cmd, cwd=workdir, stderr=STDOUT)
370
+ except CalledProcessError as e:
371
+ raise RuntimeError(
372
+ "'%s' exited abnormally with the following output:\n%s" %
373
+ (' '.join(cmd), e.output))
374
+
375
+
376
+ if viewer == "file":
377
+ shutil.move(join(workdir, src), filename)
378
+ elif viewer == "BytesIO":
379
+ with open(join(workdir, src), 'rb') as fh:
380
+ outputbuffer.write(fh.read())
381
+ elif callable(viewer):
382
+ viewer(join(workdir, src), fmt=output)
383
+ else:
384
+ try:
385
+ _check_output_no_window(
386
+ [viewer, src], cwd=workdir, stderr=STDOUT)
387
+ except CalledProcessError as e:
388
+ raise RuntimeError(
389
+ "'%s %s' exited abnormally with the following output:\n%s" %
390
+ (viewer, src, e.output))
env-llmeval/lib/python3.10/site-packages/sympy/printing/printer.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Printing subsystem driver
2
+
3
+ SymPy's printing system works the following way: Any expression can be
4
+ passed to a designated Printer who then is responsible to return an
5
+ adequate representation of that expression.
6
+
7
+ **The basic concept is the following:**
8
+
9
+ 1. Let the object print itself if it knows how.
10
+ 2. Take the best fitting method defined in the printer.
11
+ 3. As fall-back use the emptyPrinter method for the printer.
12
+
13
+ Which Method is Responsible for Printing?
14
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15
+
16
+ The whole printing process is started by calling ``.doprint(expr)`` on the printer
17
+ which you want to use. This method looks for an appropriate method which can
18
+ print the given expression in the given style that the printer defines.
19
+ While looking for the method, it follows these steps:
20
+
21
+ 1. **Let the object print itself if it knows how.**
22
+
23
+ The printer looks for a specific method in every object. The name of that method
24
+ depends on the specific printer and is defined under ``Printer.printmethod``.
25
+ For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``.
26
+ Look at the documentation of the printer that you want to use.
27
+ The name of the method is specified there.
28
+
29
+ This was the original way of doing printing in sympy. Every class had
30
+ its own latex, mathml, str and repr methods, but it turned out that it
31
+ is hard to produce a high quality printer, if all the methods are spread
32
+ out that far. Therefore all printing code was combined into the different
33
+ printers, which works great for built-in SymPy objects, but not that
34
+ good for user defined classes where it is inconvenient to patch the
35
+ printers.
36
+
37
+ 2. **Take the best fitting method defined in the printer.**
38
+
39
+ The printer loops through expr classes (class + its bases), and tries
40
+ to dispatch the work to ``_print_<EXPR_CLASS>``
41
+
42
+ e.g., suppose we have the following class hierarchy::
43
+
44
+ Basic
45
+ |
46
+ Atom
47
+ |
48
+ Number
49
+ |
50
+ Rational
51
+
52
+ then, for ``expr=Rational(...)``, the Printer will try
53
+ to call printer methods in the order as shown in the figure below::
54
+
55
+ p._print(expr)
56
+ |
57
+ |-- p._print_Rational(expr)
58
+ |
59
+ |-- p._print_Number(expr)
60
+ |
61
+ |-- p._print_Atom(expr)
62
+ |
63
+ `-- p._print_Basic(expr)
64
+
65
+ if ``._print_Rational`` method exists in the printer, then it is called,
66
+ and the result is returned back. Otherwise, the printer tries to call
67
+ ``._print_Number`` and so on.
68
+
69
+ 3. **As a fall-back use the emptyPrinter method for the printer.**
70
+
71
+ As fall-back ``self.emptyPrinter`` will be called with the expression. If
72
+ not defined in the Printer subclass this will be the same as ``str(expr)``.
73
+
74
+ .. _printer_example:
75
+
76
+ Example of Custom Printer
77
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
78
+
79
+ In the example below, we have a printer which prints the derivative of a function
80
+ in a shorter form.
81
+
82
+ .. code-block:: python
83
+
84
+ from sympy.core.symbol import Symbol
85
+ from sympy.printing.latex import LatexPrinter, print_latex
86
+ from sympy.core.function import UndefinedFunction, Function
87
+
88
+
89
+ class MyLatexPrinter(LatexPrinter):
90
+ \"\"\"Print derivative of a function of symbols in a shorter form.
91
+ \"\"\"
92
+ def _print_Derivative(self, expr):
93
+ function, *vars = expr.args
94
+ if not isinstance(type(function), UndefinedFunction) or \\
95
+ not all(isinstance(i, Symbol) for i in vars):
96
+ return super()._print_Derivative(expr)
97
+
98
+ # If you want the printer to work correctly for nested
99
+ # expressions then use self._print() instead of str() or latex().
100
+ # See the example of nested modulo below in the custom printing
101
+ # method section.
102
+ return "{}_{{{}}}".format(
103
+ self._print(Symbol(function.func.__name__)),
104
+ ''.join(self._print(i) for i in vars))
105
+
106
+
107
+ def print_my_latex(expr):
108
+ \"\"\" Most of the printers define their own wrappers for print().
109
+ These wrappers usually take printer settings. Our printer does not have
110
+ any settings.
111
+ \"\"\"
112
+ print(MyLatexPrinter().doprint(expr))
113
+
114
+
115
+ y = Symbol("y")
116
+ x = Symbol("x")
117
+ f = Function("f")
118
+ expr = f(x, y).diff(x, y)
119
+
120
+ # Print the expression using the normal latex printer and our custom
121
+ # printer.
122
+ print_latex(expr)
123
+ print_my_latex(expr)
124
+
125
+ The output of the code above is::
126
+
127
+ \\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)}
128
+ f_{xy}
129
+
130
+ .. _printer_method_example:
131
+
132
+ Example of Custom Printing Method
133
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
134
+
135
+ In the example below, the latex printing of the modulo operator is modified.
136
+ This is done by overriding the method ``_latex`` of ``Mod``.
137
+
138
+ >>> from sympy import Symbol, Mod, Integer, print_latex
139
+
140
+ >>> # Always use printer._print()
141
+ >>> class ModOp(Mod):
142
+ ... def _latex(self, printer):
143
+ ... a, b = [printer._print(i) for i in self.args]
144
+ ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
145
+
146
+ Comparing the output of our custom operator to the builtin one:
147
+
148
+ >>> x = Symbol('x')
149
+ >>> m = Symbol('m')
150
+ >>> print_latex(Mod(x, m))
151
+ x \\bmod m
152
+ >>> print_latex(ModOp(x, m))
153
+ \\operatorname{Mod}{\\left(x, m\\right)}
154
+
155
+ Common mistakes
156
+ ~~~~~~~~~~~~~~~
157
+ It's important to always use ``self._print(obj)`` to print subcomponents of
158
+ an expression when customizing a printer. Mistakes include:
159
+
160
+ 1. Using ``self.doprint(obj)`` instead:
161
+
162
+ >>> # This example does not work properly, as only the outermost call may use
163
+ >>> # doprint.
164
+ >>> class ModOpModeWrong(Mod):
165
+ ... def _latex(self, printer):
166
+ ... a, b = [printer.doprint(i) for i in self.args]
167
+ ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
168
+
169
+ This fails when the ``mode`` argument is passed to the printer:
170
+
171
+ >>> print_latex(ModOp(x, m), mode='inline') # ok
172
+ $\\operatorname{Mod}{\\left(x, m\\right)}$
173
+ >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad
174
+ $\\operatorname{Mod}{\\left($x$, $m$\\right)}$
175
+
176
+ 2. Using ``str(obj)`` instead:
177
+
178
+ >>> class ModOpNestedWrong(Mod):
179
+ ... def _latex(self, printer):
180
+ ... a, b = [str(i) for i in self.args]
181
+ ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
182
+
183
+ This fails on nested objects:
184
+
185
+ >>> # Nested modulo.
186
+ >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok
187
+ \\operatorname{Mod}{\\left(\\operatorname{Mod}{\\left(x, m\\right)}, 7\\right)}
188
+ >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad
189
+ \\operatorname{Mod}{\\left(ModOpNestedWrong(x, m), 7\\right)}
190
+
191
+ 3. Using ``LatexPrinter()._print(obj)`` instead.
192
+
193
+ >>> from sympy.printing.latex import LatexPrinter
194
+ >>> class ModOpSettingsWrong(Mod):
195
+ ... def _latex(self, printer):
196
+ ... a, b = [LatexPrinter()._print(i) for i in self.args]
197
+ ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
198
+
199
+ This causes all the settings to be discarded in the subobjects. As an
200
+ example, the ``full_prec`` setting which shows floats to full precision is
201
+ ignored:
202
+
203
+ >>> from sympy import Float
204
+ >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok
205
+ \\operatorname{Mod}{\\left(1.00000000000000 x, m\\right)}
206
+ >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad
207
+ \\operatorname{Mod}{\\left(1.0 x, m\\right)}
208
+
209
+ """
210
+
211
+ from __future__ import annotations
212
+ import sys
213
+ from typing import Any, Type
214
+ import inspect
215
+ from contextlib import contextmanager
216
+ from functools import cmp_to_key, update_wrapper
217
+
218
+ from sympy.core.add import Add
219
+ from sympy.core.basic import Basic
220
+
221
+ from sympy.core.function import AppliedUndef, UndefinedFunction, Function
222
+
223
+
224
+
225
+ @contextmanager
226
+ def printer_context(printer, **kwargs):
227
+ original = printer._context.copy()
228
+ try:
229
+ printer._context.update(kwargs)
230
+ yield
231
+ finally:
232
+ printer._context = original
233
+
234
+
235
+ class Printer:
236
+ """ Generic printer
237
+
238
+ Its job is to provide infrastructure for implementing new printers easily.
239
+
240
+ If you want to define your custom Printer or your custom printing method
241
+ for your custom class then see the example above: printer_example_ .
242
+ """
243
+
244
+ _global_settings: dict[str, Any] = {}
245
+
246
+ _default_settings: dict[str, Any] = {}
247
+
248
+ printmethod = None # type: str
249
+
250
+ @classmethod
251
+ def _get_initial_settings(cls):
252
+ settings = cls._default_settings.copy()
253
+ for key, val in cls._global_settings.items():
254
+ if key in cls._default_settings:
255
+ settings[key] = val
256
+ return settings
257
+
258
+ def __init__(self, settings=None):
259
+ self._str = str
260
+
261
+ self._settings = self._get_initial_settings()
262
+ self._context = {} # mutable during printing
263
+
264
+ if settings is not None:
265
+ self._settings.update(settings)
266
+
267
+ if len(self._settings) > len(self._default_settings):
268
+ for key in self._settings:
269
+ if key not in self._default_settings:
270
+ raise TypeError("Unknown setting '%s'." % key)
271
+
272
+ # _print_level is the number of times self._print() was recursively
273
+ # called. See StrPrinter._print_Float() for an example of usage
274
+ self._print_level = 0
275
+
276
+ @classmethod
277
+ def set_global_settings(cls, **settings):
278
+ """Set system-wide printing settings. """
279
+ for key, val in settings.items():
280
+ if val is not None:
281
+ cls._global_settings[key] = val
282
+
283
+ @property
284
+ def order(self):
285
+ if 'order' in self._settings:
286
+ return self._settings['order']
287
+ else:
288
+ raise AttributeError("No order defined.")
289
+
290
+ def doprint(self, expr):
291
+ """Returns printer's representation for expr (as a string)"""
292
+ return self._str(self._print(expr))
293
+
294
+ def _print(self, expr, **kwargs) -> str:
295
+ """Internal dispatcher
296
+
297
+ Tries the following concepts to print an expression:
298
+ 1. Let the object print itself if it knows how.
299
+ 2. Take the best fitting method defined in the printer.
300
+ 3. As fall-back use the emptyPrinter method for the printer.
301
+ """
302
+ self._print_level += 1
303
+ try:
304
+ # If the printer defines a name for a printing method
305
+ # (Printer.printmethod) and the object knows for itself how it
306
+ # should be printed, use that method.
307
+ if self.printmethod and hasattr(expr, self.printmethod):
308
+ if not (isinstance(expr, type) and issubclass(expr, Basic)):
309
+ return getattr(expr, self.printmethod)(self, **kwargs)
310
+
311
+ # See if the class of expr is known, or if one of its super
312
+ # classes is known, and use that print function
313
+ # Exception: ignore the subclasses of Undefined, so that, e.g.,
314
+ # Function('gamma') does not get dispatched to _print_gamma
315
+ classes = type(expr).__mro__
316
+ if AppliedUndef in classes:
317
+ classes = classes[classes.index(AppliedUndef):]
318
+ if UndefinedFunction in classes:
319
+ classes = classes[classes.index(UndefinedFunction):]
320
+ # Another exception: if someone subclasses a known function, e.g.,
321
+ # gamma, and changes the name, then ignore _print_gamma
322
+ if Function in classes:
323
+ i = classes.index(Function)
324
+ classes = tuple(c for c in classes[:i] if \
325
+ c.__name__ == classes[0].__name__ or \
326
+ c.__name__.endswith("Base")) + classes[i:]
327
+ for cls in classes:
328
+ printmethodname = '_print_' + cls.__name__
329
+ printmethod = getattr(self, printmethodname, None)
330
+ if printmethod is not None:
331
+ return printmethod(expr, **kwargs)
332
+ # Unknown object, fall back to the emptyPrinter.
333
+ return self.emptyPrinter(expr)
334
+ finally:
335
+ self._print_level -= 1
336
+
337
+ def emptyPrinter(self, expr):
338
+ return str(expr)
339
+
340
+ def _as_ordered_terms(self, expr, order=None):
341
+ """A compatibility function for ordering terms in Add. """
342
+ order = order or self.order
343
+
344
+ if order == 'old':
345
+ return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty))
346
+ elif order == 'none':
347
+ return list(expr.args)
348
+ else:
349
+ return expr.as_ordered_terms(order=order)
350
+
351
+
352
+ class _PrintFunction:
353
+ """
354
+ Function wrapper to replace ``**settings`` in the signature with printer defaults
355
+ """
356
+ def __init__(self, f, print_cls: Type[Printer]):
357
+ # find all the non-setting arguments
358
+ params = list(inspect.signature(f).parameters.values())
359
+ assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD
360
+ self.__other_params = params
361
+
362
+ self.__print_cls = print_cls
363
+ update_wrapper(self, f)
364
+
365
+ def __reduce__(self):
366
+ # Since this is used as a decorator, it replaces the original function.
367
+ # The default pickling will try to pickle self.__wrapped__ and fail
368
+ # because the wrapped function can't be retrieved by name.
369
+ return self.__wrapped__.__qualname__
370
+
371
+ def __call__(self, *args, **kwargs):
372
+ return self.__wrapped__(*args, **kwargs)
373
+
374
+ @property
375
+ def __signature__(self) -> inspect.Signature:
376
+ settings = self.__print_cls._get_initial_settings()
377
+ return inspect.Signature(
378
+ parameters=self.__other_params + [
379
+ inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v)
380
+ for k, v in settings.items()
381
+ ],
382
+ return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore
383
+ )
384
+
385
+
386
+ def print_function(print_cls):
387
+ """ A decorator to replace kwargs with the printer settings in __signature__ """
388
+ def decorator(f):
389
+ if sys.version_info < (3, 9):
390
+ # We have to create a subclass so that `help` actually shows the docstring in older Python versions.
391
+ # IPython and Sphinx do not need this, only a raw Python console.
392
+ cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), {"__doc__": f.__doc__})
393
+ else:
394
+ cls = _PrintFunction
395
+ return cls(f, print_cls)
396
+ return decorator
env-llmeval/lib/python3.10/site-packages/sympy/printing/pycode.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python code printers
3
+
4
+ This module contains Python code printers for plain Python as well as NumPy & SciPy enabled code.
5
+ """
6
+ from collections import defaultdict
7
+ from itertools import chain
8
+ from sympy.core import S
9
+ from sympy.core.mod import Mod
10
+ from .precedence import precedence
11
+ from .codeprinter import CodePrinter
12
+
13
+ _kw = {
14
+ 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
15
+ 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in',
16
+ 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
17
+ 'with', 'yield', 'None', 'False', 'nonlocal', 'True'
18
+ }
19
+
20
+ _known_functions = {
21
+ 'Abs': 'abs',
22
+ 'Min': 'min',
23
+ 'Max': 'max',
24
+ }
25
+ _known_functions_math = {
26
+ 'acos': 'acos',
27
+ 'acosh': 'acosh',
28
+ 'asin': 'asin',
29
+ 'asinh': 'asinh',
30
+ 'atan': 'atan',
31
+ 'atan2': 'atan2',
32
+ 'atanh': 'atanh',
33
+ 'ceiling': 'ceil',
34
+ 'cos': 'cos',
35
+ 'cosh': 'cosh',
36
+ 'erf': 'erf',
37
+ 'erfc': 'erfc',
38
+ 'exp': 'exp',
39
+ 'expm1': 'expm1',
40
+ 'factorial': 'factorial',
41
+ 'floor': 'floor',
42
+ 'gamma': 'gamma',
43
+ 'hypot': 'hypot',
44
+ 'loggamma': 'lgamma',
45
+ 'log': 'log',
46
+ 'ln': 'log',
47
+ 'log10': 'log10',
48
+ 'log1p': 'log1p',
49
+ 'log2': 'log2',
50
+ 'sin': 'sin',
51
+ 'sinh': 'sinh',
52
+ 'Sqrt': 'sqrt',
53
+ 'tan': 'tan',
54
+ 'tanh': 'tanh'
55
+ } # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf
56
+ # radians trunc fmod fsum gcd degrees fabs]
57
+ _known_constants_math = {
58
+ 'Exp1': 'e',
59
+ 'Pi': 'pi',
60
+ 'E': 'e',
61
+ 'Infinity': 'inf',
62
+ 'NaN': 'nan',
63
+ 'ComplexInfinity': 'nan'
64
+ }
65
+
66
+ def _print_known_func(self, expr):
67
+ known = self.known_functions[expr.__class__.__name__]
68
+ return '{name}({args})'.format(name=self._module_format(known),
69
+ args=', '.join((self._print(arg) for arg in expr.args)))
70
+
71
+
72
+ def _print_known_const(self, expr):
73
+ known = self.known_constants[expr.__class__.__name__]
74
+ return self._module_format(known)
75
+
76
+
77
+ class AbstractPythonCodePrinter(CodePrinter):
78
+ printmethod = "_pythoncode"
79
+ language = "Python"
80
+ reserved_words = _kw
81
+ modules = None # initialized to a set in __init__
82
+ tab = ' '
83
+ _kf = dict(chain(
84
+ _known_functions.items(),
85
+ [(k, 'math.' + v) for k, v in _known_functions_math.items()]
86
+ ))
87
+ _kc = {k: 'math.'+v for k, v in _known_constants_math.items()}
88
+ _operators = {'and': 'and', 'or': 'or', 'not': 'not'}
89
+ _default_settings = dict(
90
+ CodePrinter._default_settings,
91
+ user_functions={},
92
+ precision=17,
93
+ inline=True,
94
+ fully_qualified_modules=True,
95
+ contract=False,
96
+ standard='python3',
97
+ )
98
+
99
+ def __init__(self, settings=None):
100
+ super().__init__(settings)
101
+
102
+ # Python standard handler
103
+ std = self._settings['standard']
104
+ if std is None:
105
+ import sys
106
+ std = 'python{}'.format(sys.version_info.major)
107
+ if std != 'python3':
108
+ raise ValueError('Only Python 3 is supported.')
109
+ self.standard = std
110
+
111
+ self.module_imports = defaultdict(set)
112
+
113
+ # Known functions and constants handler
114
+ self.known_functions = dict(self._kf, **(settings or {}).get(
115
+ 'user_functions', {}))
116
+ self.known_constants = dict(self._kc, **(settings or {}).get(
117
+ 'user_constants', {}))
118
+
119
+ def _declare_number_const(self, name, value):
120
+ return "%s = %s" % (name, value)
121
+
122
+ def _module_format(self, fqn, register=True):
123
+ parts = fqn.split('.')
124
+ if register and len(parts) > 1:
125
+ self.module_imports['.'.join(parts[:-1])].add(parts[-1])
126
+
127
+ if self._settings['fully_qualified_modules']:
128
+ return fqn
129
+ else:
130
+ return fqn.split('(')[0].split('[')[0].split('.')[-1]
131
+
132
+ def _format_code(self, lines):
133
+ return lines
134
+
135
+ def _get_statement(self, codestring):
136
+ return "{}".format(codestring)
137
+
138
+ def _get_comment(self, text):
139
+ return " # {}".format(text)
140
+
141
+ def _expand_fold_binary_op(self, op, args):
142
+ """
143
+ This method expands a fold on binary operations.
144
+
145
+ ``functools.reduce`` is an example of a folded operation.
146
+
147
+ For example, the expression
148
+
149
+ `A + B + C + D`
150
+
151
+ is folded into
152
+
153
+ `((A + B) + C) + D`
154
+ """
155
+ if len(args) == 1:
156
+ return self._print(args[0])
157
+ else:
158
+ return "%s(%s, %s)" % (
159
+ self._module_format(op),
160
+ self._expand_fold_binary_op(op, args[:-1]),
161
+ self._print(args[-1]),
162
+ )
163
+
164
+ def _expand_reduce_binary_op(self, op, args):
165
+ """
166
+ This method expands a reductin on binary operations.
167
+
168
+ Notice: this is NOT the same as ``functools.reduce``.
169
+
170
+ For example, the expression
171
+
172
+ `A + B + C + D`
173
+
174
+ is reduced into:
175
+
176
+ `(A + B) + (C + D)`
177
+ """
178
+ if len(args) == 1:
179
+ return self._print(args[0])
180
+ else:
181
+ N = len(args)
182
+ Nhalf = N // 2
183
+ return "%s(%s, %s)" % (
184
+ self._module_format(op),
185
+ self._expand_reduce_binary_op(args[:Nhalf]),
186
+ self._expand_reduce_binary_op(args[Nhalf:]),
187
+ )
188
+
189
+ def _print_NaN(self, expr):
190
+ return "float('nan')"
191
+
192
+ def _print_Infinity(self, expr):
193
+ return "float('inf')"
194
+
195
+ def _print_NegativeInfinity(self, expr):
196
+ return "float('-inf')"
197
+
198
+ def _print_ComplexInfinity(self, expr):
199
+ return self._print_NaN(expr)
200
+
201
+ def _print_Mod(self, expr):
202
+ PREC = precedence(expr)
203
+ return ('{} % {}'.format(*(self.parenthesize(x, PREC) for x in expr.args)))
204
+
205
+ def _print_Piecewise(self, expr):
206
+ result = []
207
+ i = 0
208
+ for arg in expr.args:
209
+ e = arg.expr
210
+ c = arg.cond
211
+ if i == 0:
212
+ result.append('(')
213
+ result.append('(')
214
+ result.append(self._print(e))
215
+ result.append(')')
216
+ result.append(' if ')
217
+ result.append(self._print(c))
218
+ result.append(' else ')
219
+ i += 1
220
+ result = result[:-1]
221
+ if result[-1] == 'True':
222
+ result = result[:-2]
223
+ result.append(')')
224
+ else:
225
+ result.append(' else None)')
226
+ return ''.join(result)
227
+
228
+ def _print_Relational(self, expr):
229
+ "Relational printer for Equality and Unequality"
230
+ op = {
231
+ '==' :'equal',
232
+ '!=' :'not_equal',
233
+ '<' :'less',
234
+ '<=' :'less_equal',
235
+ '>' :'greater',
236
+ '>=' :'greater_equal',
237
+ }
238
+ if expr.rel_op in op:
239
+ lhs = self._print(expr.lhs)
240
+ rhs = self._print(expr.rhs)
241
+ return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs)
242
+ return super()._print_Relational(expr)
243
+
244
+ def _print_ITE(self, expr):
245
+ from sympy.functions.elementary.piecewise import Piecewise
246
+ return self._print(expr.rewrite(Piecewise))
247
+
248
+ def _print_Sum(self, expr):
249
+ loops = (
250
+ 'for {i} in range({a}, {b}+1)'.format(
251
+ i=self._print(i),
252
+ a=self._print(a),
253
+ b=self._print(b))
254
+ for i, a, b in expr.limits)
255
+ return '(builtins.sum({function} {loops}))'.format(
256
+ function=self._print(expr.function),
257
+ loops=' '.join(loops))
258
+
259
+ def _print_ImaginaryUnit(self, expr):
260
+ return '1j'
261
+
262
+ def _print_KroneckerDelta(self, expr):
263
+ a, b = expr.args
264
+
265
+ return '(1 if {a} == {b} else 0)'.format(
266
+ a = self._print(a),
267
+ b = self._print(b)
268
+ )
269
+
270
+ def _print_MatrixBase(self, expr):
271
+ name = expr.__class__.__name__
272
+ func = self.known_functions.get(name, name)
273
+ return "%s(%s)" % (func, self._print(expr.tolist()))
274
+
275
+ _print_SparseRepMatrix = \
276
+ _print_MutableSparseMatrix = \
277
+ _print_ImmutableSparseMatrix = \
278
+ _print_Matrix = \
279
+ _print_DenseMatrix = \
280
+ _print_MutableDenseMatrix = \
281
+ _print_ImmutableMatrix = \
282
+ _print_ImmutableDenseMatrix = \
283
+ lambda self, expr: self._print_MatrixBase(expr)
284
+
285
+ def _indent_codestring(self, codestring):
286
+ return '\n'.join([self.tab + line for line in codestring.split('\n')])
287
+
288
+ def _print_FunctionDefinition(self, fd):
289
+ body = '\n'.join((self._print(arg) for arg in fd.body))
290
+ return "def {name}({parameters}):\n{body}".format(
291
+ name=self._print(fd.name),
292
+ parameters=', '.join([self._print(var.symbol) for var in fd.parameters]),
293
+ body=self._indent_codestring(body)
294
+ )
295
+
296
+ def _print_While(self, whl):
297
+ body = '\n'.join((self._print(arg) for arg in whl.body))
298
+ return "while {cond}:\n{body}".format(
299
+ cond=self._print(whl.condition),
300
+ body=self._indent_codestring(body)
301
+ )
302
+
303
+ def _print_Declaration(self, decl):
304
+ return '%s = %s' % (
305
+ self._print(decl.variable.symbol),
306
+ self._print(decl.variable.value)
307
+ )
308
+
309
+ def _print_Return(self, ret):
310
+ arg, = ret.args
311
+ return 'return %s' % self._print(arg)
312
+
313
+ def _print_Print(self, prnt):
314
+ print_args = ', '.join((self._print(arg) for arg in prnt.print_args))
315
+ if prnt.format_string != None: # Must be '!= None', cannot be 'is not None'
316
+ print_args = '{} % ({})'.format(
317
+ self._print(prnt.format_string), print_args)
318
+ if prnt.file != None: # Must be '!= None', cannot be 'is not None'
319
+ print_args += ', file=%s' % self._print(prnt.file)
320
+
321
+ return 'print(%s)' % print_args
322
+
323
+ def _print_Stream(self, strm):
324
+ if str(strm.name) == 'stdout':
325
+ return self._module_format('sys.stdout')
326
+ elif str(strm.name) == 'stderr':
327
+ return self._module_format('sys.stderr')
328
+ else:
329
+ return self._print(strm.name)
330
+
331
+ def _print_NoneToken(self, arg):
332
+ return 'None'
333
+
334
+ def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'):
335
+ """Printing helper function for ``Pow``
336
+
337
+ Notes
338
+ =====
339
+
340
+ This preprocesses the ``sqrt`` as math formatter and prints division
341
+
342
+ Examples
343
+ ========
344
+
345
+ >>> from sympy import sqrt
346
+ >>> from sympy.printing.pycode import PythonCodePrinter
347
+ >>> from sympy.abc import x
348
+
349
+ Python code printer automatically looks up ``math.sqrt``.
350
+
351
+ >>> printer = PythonCodePrinter()
352
+ >>> printer._hprint_Pow(sqrt(x), rational=True)
353
+ 'x**(1/2)'
354
+ >>> printer._hprint_Pow(sqrt(x), rational=False)
355
+ 'math.sqrt(x)'
356
+ >>> printer._hprint_Pow(1/sqrt(x), rational=True)
357
+ 'x**(-1/2)'
358
+ >>> printer._hprint_Pow(1/sqrt(x), rational=False)
359
+ '1/math.sqrt(x)'
360
+ >>> printer._hprint_Pow(1/x, rational=False)
361
+ '1/x'
362
+ >>> printer._hprint_Pow(1/x, rational=True)
363
+ 'x**(-1)'
364
+
365
+ Using sqrt from numpy or mpmath
366
+
367
+ >>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt')
368
+ 'numpy.sqrt(x)'
369
+ >>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt')
370
+ 'mpmath.sqrt(x)'
371
+
372
+ See Also
373
+ ========
374
+
375
+ sympy.printing.str.StrPrinter._print_Pow
376
+ """
377
+ PREC = precedence(expr)
378
+
379
+ if expr.exp == S.Half and not rational:
380
+ func = self._module_format(sqrt)
381
+ arg = self._print(expr.base)
382
+ return '{func}({arg})'.format(func=func, arg=arg)
383
+
384
+ if expr.is_commutative and not rational:
385
+ if -expr.exp is S.Half:
386
+ func = self._module_format(sqrt)
387
+ num = self._print(S.One)
388
+ arg = self._print(expr.base)
389
+ return f"{num}/{func}({arg})"
390
+ if expr.exp is S.NegativeOne:
391
+ num = self._print(S.One)
392
+ arg = self.parenthesize(expr.base, PREC, strict=False)
393
+ return f"{num}/{arg}"
394
+
395
+
396
+ base_str = self.parenthesize(expr.base, PREC, strict=False)
397
+ exp_str = self.parenthesize(expr.exp, PREC, strict=False)
398
+ return "{}**{}".format(base_str, exp_str)
399
+
400
+
401
+ class ArrayPrinter:
402
+
403
+ def _arrayify(self, indexed):
404
+ from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
405
+ try:
406
+ return convert_indexed_to_array(indexed)
407
+ except Exception:
408
+ return indexed
409
+
410
+ def _get_einsum_string(self, subranks, contraction_indices):
411
+ letters = self._get_letter_generator_for_einsum()
412
+ contraction_string = ""
413
+ counter = 0
414
+ d = {j: min(i) for i in contraction_indices for j in i}
415
+ indices = []
416
+ for rank_arg in subranks:
417
+ lindices = []
418
+ for i in range(rank_arg):
419
+ if counter in d:
420
+ lindices.append(d[counter])
421
+ else:
422
+ lindices.append(counter)
423
+ counter += 1
424
+ indices.append(lindices)
425
+ mapping = {}
426
+ letters_free = []
427
+ letters_dum = []
428
+ for i in indices:
429
+ for j in i:
430
+ if j not in mapping:
431
+ l = next(letters)
432
+ mapping[j] = l
433
+ else:
434
+ l = mapping[j]
435
+ contraction_string += l
436
+ if j in d:
437
+ if l not in letters_dum:
438
+ letters_dum.append(l)
439
+ else:
440
+ letters_free.append(l)
441
+ contraction_string += ","
442
+ contraction_string = contraction_string[:-1]
443
+ return contraction_string, letters_free, letters_dum
444
+
445
+ def _get_letter_generator_for_einsum(self):
446
+ for i in range(97, 123):
447
+ yield chr(i)
448
+ for i in range(65, 91):
449
+ yield chr(i)
450
+ raise ValueError("out of letters")
451
+
452
+ def _print_ArrayTensorProduct(self, expr):
453
+ letters = self._get_letter_generator_for_einsum()
454
+ contraction_string = ",".join(["".join([next(letters) for j in range(i)]) for i in expr.subranks])
455
+ return '%s("%s", %s)' % (
456
+ self._module_format(self._module + "." + self._einsum),
457
+ contraction_string,
458
+ ", ".join([self._print(arg) for arg in expr.args])
459
+ )
460
+
461
+ def _print_ArrayContraction(self, expr):
462
+ from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
463
+ base = expr.expr
464
+ contraction_indices = expr.contraction_indices
465
+
466
+ if isinstance(base, ArrayTensorProduct):
467
+ elems = ",".join(["%s" % (self._print(arg)) for arg in base.args])
468
+ ranks = base.subranks
469
+ else:
470
+ elems = self._print(base)
471
+ ranks = [len(base.shape)]
472
+
473
+ contraction_string, letters_free, letters_dum = self._get_einsum_string(ranks, contraction_indices)
474
+
475
+ if not contraction_indices:
476
+ return self._print(base)
477
+ if isinstance(base, ArrayTensorProduct):
478
+ elems = ",".join(["%s" % (self._print(arg)) for arg in base.args])
479
+ else:
480
+ elems = self._print(base)
481
+ return "%s(\"%s\", %s)" % (
482
+ self._module_format(self._module + "." + self._einsum),
483
+ "{}->{}".format(contraction_string, "".join(sorted(letters_free))),
484
+ elems,
485
+ )
486
+
487
+ def _print_ArrayDiagonal(self, expr):
488
+ from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
489
+ diagonal_indices = list(expr.diagonal_indices)
490
+ if isinstance(expr.expr, ArrayTensorProduct):
491
+ subranks = expr.expr.subranks
492
+ elems = expr.expr.args
493
+ else:
494
+ subranks = expr.subranks
495
+ elems = [expr.expr]
496
+ diagonal_string, letters_free, letters_dum = self._get_einsum_string(subranks, diagonal_indices)
497
+ elems = [self._print(i) for i in elems]
498
+ return '%s("%s", %s)' % (
499
+ self._module_format(self._module + "." + self._einsum),
500
+ "{}->{}".format(diagonal_string, "".join(letters_free+letters_dum)),
501
+ ", ".join(elems)
502
+ )
503
+
504
+ def _print_PermuteDims(self, expr):
505
+ return "%s(%s, %s)" % (
506
+ self._module_format(self._module + "." + self._transpose),
507
+ self._print(expr.expr),
508
+ self._print(expr.permutation.array_form),
509
+ )
510
+
511
+ def _print_ArrayAdd(self, expr):
512
+ return self._expand_fold_binary_op(self._module + "." + self._add, expr.args)
513
+
514
+ def _print_OneArray(self, expr):
515
+ return "%s((%s,))" % (
516
+ self._module_format(self._module+ "." + self._ones),
517
+ ','.join(map(self._print,expr.args))
518
+ )
519
+
520
+ def _print_ZeroArray(self, expr):
521
+ return "%s((%s,))" % (
522
+ self._module_format(self._module+ "." + self._zeros),
523
+ ','.join(map(self._print,expr.args))
524
+ )
525
+
526
+ def _print_Assignment(self, expr):
527
+ #XXX: maybe this needs to happen at a higher level e.g. at _print or
528
+ #doprint?
529
+ lhs = self._print(self._arrayify(expr.lhs))
530
+ rhs = self._print(self._arrayify(expr.rhs))
531
+ return "%s = %s" % ( lhs, rhs )
532
+
533
+ def _print_IndexedBase(self, expr):
534
+ return self._print_ArraySymbol(expr)
535
+
536
+
537
+ class PythonCodePrinter(AbstractPythonCodePrinter):
538
+
539
+ def _print_sign(self, e):
540
+ return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(
541
+ f=self._module_format('math.copysign'), e=self._print(e.args[0]))
542
+
543
+ def _print_Not(self, expr):
544
+ PREC = precedence(expr)
545
+ return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
546
+
547
+ def _print_Indexed(self, expr):
548
+ base = expr.args[0]
549
+ index = expr.args[1:]
550
+ return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))
551
+
552
+ def _print_Pow(self, expr, rational=False):
553
+ return self._hprint_Pow(expr, rational=rational)
554
+
555
+ def _print_Rational(self, expr):
556
+ return '{}/{}'.format(expr.p, expr.q)
557
+
558
+ def _print_Half(self, expr):
559
+ return self._print_Rational(expr)
560
+
561
+ def _print_frac(self, expr):
562
+ return self._print_Mod(Mod(expr.args[0], 1))
563
+
564
+ def _print_Symbol(self, expr):
565
+
566
+ name = super()._print_Symbol(expr)
567
+
568
+ if name in self.reserved_words:
569
+ if self._settings['error_on_reserved']:
570
+ msg = ('This expression includes the symbol "{}" which is a '
571
+ 'reserved keyword in this language.')
572
+ raise ValueError(msg.format(name))
573
+ return name + self._settings['reserved_word_suffix']
574
+ elif '{' in name: # Remove curly braces from subscripted variables
575
+ return name.replace('{', '').replace('}', '')
576
+ else:
577
+ return name
578
+
579
+ _print_lowergamma = CodePrinter._print_not_supported
580
+ _print_uppergamma = CodePrinter._print_not_supported
581
+ _print_fresnelc = CodePrinter._print_not_supported
582
+ _print_fresnels = CodePrinter._print_not_supported
583
+
584
+
585
+ for k in PythonCodePrinter._kf:
586
+ setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func)
587
+
588
+ for k in _known_constants_math:
589
+ setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const)
590
+
591
+
592
+ def pycode(expr, **settings):
593
+ """ Converts an expr to a string of Python code
594
+
595
+ Parameters
596
+ ==========
597
+
598
+ expr : Expr
599
+ A SymPy expression.
600
+ fully_qualified_modules : bool
601
+ Whether or not to write out full module names of functions
602
+ (``math.sin`` vs. ``sin``). default: ``True``.
603
+ standard : str or None, optional
604
+ Only 'python3' (default) is supported.
605
+ This parameter may be removed in the future.
606
+
607
+ Examples
608
+ ========
609
+
610
+ >>> from sympy import pycode, tan, Symbol
611
+ >>> pycode(tan(Symbol('x')) + 1)
612
+ 'math.tan(x) + 1'
613
+
614
+ """
615
+ return PythonCodePrinter(settings).doprint(expr)
616
+
617
+
618
+ _not_in_mpmath = 'log1p log2'.split()
619
+ _in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath]
620
+ _known_functions_mpmath = dict(_in_mpmath, **{
621
+ 'beta': 'beta',
622
+ 'frac': 'frac',
623
+ 'fresnelc': 'fresnelc',
624
+ 'fresnels': 'fresnels',
625
+ 'sign': 'sign',
626
+ 'loggamma': 'loggamma',
627
+ 'hyper': 'hyper',
628
+ 'meijerg': 'meijerg',
629
+ 'besselj': 'besselj',
630
+ 'bessely': 'bessely',
631
+ 'besseli': 'besseli',
632
+ 'besselk': 'besselk',
633
+ })
634
+ _known_constants_mpmath = {
635
+ 'Exp1': 'e',
636
+ 'Pi': 'pi',
637
+ 'GoldenRatio': 'phi',
638
+ 'EulerGamma': 'euler',
639
+ 'Catalan': 'catalan',
640
+ 'NaN': 'nan',
641
+ 'Infinity': 'inf',
642
+ 'NegativeInfinity': 'ninf'
643
+ }
644
+
645
+
646
+ def _unpack_integral_limits(integral_expr):
647
+ """ helper function for _print_Integral that
648
+ - accepts an Integral expression
649
+ - returns a tuple of
650
+ - a list variables of integration
651
+ - a list of tuples of the upper and lower limits of integration
652
+ """
653
+ integration_vars = []
654
+ limits = []
655
+ for integration_range in integral_expr.limits:
656
+ if len(integration_range) == 3:
657
+ integration_var, lower_limit, upper_limit = integration_range
658
+ else:
659
+ raise NotImplementedError("Only definite integrals are supported")
660
+ integration_vars.append(integration_var)
661
+ limits.append((lower_limit, upper_limit))
662
+ return integration_vars, limits
663
+
664
+
665
+ class MpmathPrinter(PythonCodePrinter):
666
+ """
667
+ Lambda printer for mpmath which maintains precision for floats
668
+ """
669
+ printmethod = "_mpmathcode"
670
+
671
+ language = "Python with mpmath"
672
+
673
+ _kf = dict(chain(
674
+ _known_functions.items(),
675
+ [(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()]
676
+ ))
677
+ _kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()}
678
+
679
+ def _print_Float(self, e):
680
+ # XXX: This does not handle setting mpmath.mp.dps. It is assumed that
681
+ # the caller of the lambdified function will have set it to sufficient
682
+ # precision to match the Floats in the expression.
683
+
684
+ # Remove 'mpz' if gmpy is installed.
685
+ args = str(tuple(map(int, e._mpf_)))
686
+ return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args)
687
+
688
+
689
+ def _print_Rational(self, e):
690
+ return "{func}({p})/{func}({q})".format(
691
+ func=self._module_format('mpmath.mpf'),
692
+ q=self._print(e.q),
693
+ p=self._print(e.p)
694
+ )
695
+
696
+ def _print_Half(self, e):
697
+ return self._print_Rational(e)
698
+
699
+ def _print_uppergamma(self, e):
700
+ return "{}({}, {}, {})".format(
701
+ self._module_format('mpmath.gammainc'),
702
+ self._print(e.args[0]),
703
+ self._print(e.args[1]),
704
+ self._module_format('mpmath.inf'))
705
+
706
+ def _print_lowergamma(self, e):
707
+ return "{}({}, 0, {})".format(
708
+ self._module_format('mpmath.gammainc'),
709
+ self._print(e.args[0]),
710
+ self._print(e.args[1]))
711
+
712
+ def _print_log2(self, e):
713
+ return '{0}({1})/{0}(2)'.format(
714
+ self._module_format('mpmath.log'), self._print(e.args[0]))
715
+
716
+ def _print_log1p(self, e):
717
+ return '{}({})'.format(
718
+ self._module_format('mpmath.log1p'), self._print(e.args[0]))
719
+
720
+ def _print_Pow(self, expr, rational=False):
721
+ return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt')
722
+
723
+ def _print_Integral(self, e):
724
+ integration_vars, limits = _unpack_integral_limits(e)
725
+
726
+ return "{}(lambda {}: {}, {})".format(
727
+ self._module_format("mpmath.quad"),
728
+ ", ".join(map(self._print, integration_vars)),
729
+ self._print(e.args[0]),
730
+ ", ".join("(%s, %s)" % tuple(map(self._print, l)) for l in limits))
731
+
732
+
733
+ for k in MpmathPrinter._kf:
734
+ setattr(MpmathPrinter, '_print_%s' % k, _print_known_func)
735
+
736
+ for k in _known_constants_mpmath:
737
+ setattr(MpmathPrinter, '_print_%s' % k, _print_known_const)
738
+
739
+
740
+ class SymPyPrinter(AbstractPythonCodePrinter):
741
+
742
+ language = "Python with SymPy"
743
+
744
+ def _print_Function(self, expr):
745
+ mod = expr.func.__module__ or ''
746
+ return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__),
747
+ ', '.join((self._print(arg) for arg in expr.args)))
748
+
749
+ def _print_Pow(self, expr, rational=False):
750
+ return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt')
env-llmeval/lib/python3.10/site-packages/sympy/printing/python.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import keyword as kw
2
+ import sympy
3
+ from .repr import ReprPrinter
4
+ from .str import StrPrinter
5
+
6
+ # A list of classes that should be printed using StrPrinter
7
+ STRPRINT = ("Add", "Infinity", "Integer", "Mul", "NegativeInfinity",
8
+ "Pow", "Zero")
9
+
10
+
11
+ class PythonPrinter(ReprPrinter, StrPrinter):
12
+ """A printer which converts an expression into its Python interpretation."""
13
+
14
+ def __init__(self, settings=None):
15
+ super().__init__(settings)
16
+ self.symbols = []
17
+ self.functions = []
18
+
19
+ # Create print methods for classes that should use StrPrinter instead
20
+ # of ReprPrinter.
21
+ for name in STRPRINT:
22
+ f_name = "_print_%s" % name
23
+ f = getattr(StrPrinter, f_name)
24
+ setattr(PythonPrinter, f_name, f)
25
+
26
+ def _print_Function(self, expr):
27
+ func = expr.func.__name__
28
+ if not hasattr(sympy, func) and func not in self.functions:
29
+ self.functions.append(func)
30
+ return StrPrinter._print_Function(self, expr)
31
+
32
+ # procedure (!) for defining symbols which have be defined in print_python()
33
+ def _print_Symbol(self, expr):
34
+ symbol = self._str(expr)
35
+ if symbol not in self.symbols:
36
+ self.symbols.append(symbol)
37
+ return StrPrinter._print_Symbol(self, expr)
38
+
39
+ def _print_module(self, expr):
40
+ raise ValueError('Modules in the expression are unacceptable')
41
+
42
+
43
+ def python(expr, **settings):
44
+ """Return Python interpretation of passed expression
45
+ (can be passed to the exec() function without any modifications)"""
46
+
47
+ printer = PythonPrinter(settings)
48
+ exprp = printer.doprint(expr)
49
+
50
+ result = ''
51
+ # Returning found symbols and functions
52
+ renamings = {}
53
+ for symbolname in printer.symbols:
54
+ # Remove curly braces from subscripted variables
55
+ if '{' in symbolname:
56
+ newsymbolname = symbolname.replace('{', '').replace('}', '')
57
+ renamings[sympy.Symbol(symbolname)] = newsymbolname
58
+ else:
59
+ newsymbolname = symbolname
60
+
61
+ # Escape symbol names that are reserved Python keywords
62
+ if kw.iskeyword(newsymbolname):
63
+ while True:
64
+ newsymbolname += "_"
65
+ if (newsymbolname not in printer.symbols and
66
+ newsymbolname not in printer.functions):
67
+ renamings[sympy.Symbol(
68
+ symbolname)] = sympy.Symbol(newsymbolname)
69
+ break
70
+ result += newsymbolname + ' = Symbol(\'' + symbolname + '\')\n'
71
+
72
+ for functionname in printer.functions:
73
+ newfunctionname = functionname
74
+ # Escape function names that are reserved Python keywords
75
+ if kw.iskeyword(newfunctionname):
76
+ while True:
77
+ newfunctionname += "_"
78
+ if (newfunctionname not in printer.symbols and
79
+ newfunctionname not in printer.functions):
80
+ renamings[sympy.Function(
81
+ functionname)] = sympy.Function(newfunctionname)
82
+ break
83
+ result += newfunctionname + ' = Function(\'' + functionname + '\')\n'
84
+
85
+ if renamings:
86
+ exprp = expr.subs(renamings)
87
+ result += 'e = ' + printer._str(exprp)
88
+ return result
89
+
90
+
91
+ def print_python(expr, **settings):
92
+ """Print output of python() function"""
93
+ print(python(expr, **settings))
env-llmeval/lib/python3.10/site-packages/sympy/printing/repr.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Printer for generating executable code.
3
+
4
+ The most important function here is srepr that returns a string so that the
5
+ relation eval(srepr(expr))=expr holds in an appropriate environment.
6
+ """
7
+
8
+ from __future__ import annotations
9
+ from typing import Any
10
+
11
+ from sympy.core.function import AppliedUndef
12
+ from sympy.core.mul import Mul
13
+ from mpmath.libmp import repr_dps, to_str as mlib_to_str
14
+
15
+ from .printer import Printer, print_function
16
+
17
+
18
+ class ReprPrinter(Printer):
19
+ printmethod = "_sympyrepr"
20
+
21
+ _default_settings: dict[str, Any] = {
22
+ "order": None,
23
+ "perm_cyclic" : True,
24
+ }
25
+
26
+ def reprify(self, args, sep):
27
+ """
28
+ Prints each item in `args` and joins them with `sep`.
29
+ """
30
+ return sep.join([self.doprint(item) for item in args])
31
+
32
+ def emptyPrinter(self, expr):
33
+ """
34
+ The fallback printer.
35
+ """
36
+ if isinstance(expr, str):
37
+ return expr
38
+ elif hasattr(expr, "__srepr__"):
39
+ return expr.__srepr__()
40
+ elif hasattr(expr, "args") and hasattr(expr.args, "__iter__"):
41
+ l = []
42
+ for o in expr.args:
43
+ l.append(self._print(o))
44
+ return expr.__class__.__name__ + '(%s)' % ', '.join(l)
45
+ elif hasattr(expr, "__module__") and hasattr(expr, "__name__"):
46
+ return "<'%s.%s'>" % (expr.__module__, expr.__name__)
47
+ else:
48
+ return str(expr)
49
+
50
+ def _print_Add(self, expr, order=None):
51
+ args = self._as_ordered_terms(expr, order=order)
52
+ args = map(self._print, args)
53
+ clsname = type(expr).__name__
54
+ return clsname + "(%s)" % ", ".join(args)
55
+
56
+ def _print_Cycle(self, expr):
57
+ return expr.__repr__()
58
+
59
+ def _print_Permutation(self, expr):
60
+ from sympy.combinatorics.permutations import Permutation, Cycle
61
+ from sympy.utilities.exceptions import sympy_deprecation_warning
62
+
63
+ perm_cyclic = Permutation.print_cyclic
64
+ if perm_cyclic is not None:
65
+ sympy_deprecation_warning(
66
+ f"""
67
+ Setting Permutation.print_cyclic is deprecated. Instead use
68
+ init_printing(perm_cyclic={perm_cyclic}).
69
+ """,
70
+ deprecated_since_version="1.6",
71
+ active_deprecations_target="deprecated-permutation-print_cyclic",
72
+ stacklevel=7,
73
+ )
74
+ else:
75
+ perm_cyclic = self._settings.get("perm_cyclic", True)
76
+
77
+ if perm_cyclic:
78
+ if not expr.size:
79
+ return 'Permutation()'
80
+ # before taking Cycle notation, see if the last element is
81
+ # a singleton and move it to the head of the string
82
+ s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
83
+ last = s.rfind('(')
84
+ if not last == 0 and ',' not in s[last:]:
85
+ s = s[last:] + s[:last]
86
+ return 'Permutation%s' %s
87
+ else:
88
+ s = expr.support()
89
+ if not s:
90
+ if expr.size < 5:
91
+ return 'Permutation(%s)' % str(expr.array_form)
92
+ return 'Permutation([], size=%s)' % expr.size
93
+ trim = str(expr.array_form[:s[-1] + 1]) + ', size=%s' % expr.size
94
+ use = full = str(expr.array_form)
95
+ if len(trim) < len(full):
96
+ use = trim
97
+ return 'Permutation(%s)' % use
98
+
99
+ def _print_Function(self, expr):
100
+ r = self._print(expr.func)
101
+ r += '(%s)' % ', '.join([self._print(a) for a in expr.args])
102
+ return r
103
+
104
+ def _print_Heaviside(self, expr):
105
+ # Same as _print_Function but uses pargs to suppress default value for
106
+ # 2nd arg.
107
+ r = self._print(expr.func)
108
+ r += '(%s)' % ', '.join([self._print(a) for a in expr.pargs])
109
+ return r
110
+
111
+ def _print_FunctionClass(self, expr):
112
+ if issubclass(expr, AppliedUndef):
113
+ return 'Function(%r)' % (expr.__name__)
114
+ else:
115
+ return expr.__name__
116
+
117
+ def _print_Half(self, expr):
118
+ return 'Rational(1, 2)'
119
+
120
+ def _print_RationalConstant(self, expr):
121
+ return str(expr)
122
+
123
+ def _print_AtomicExpr(self, expr):
124
+ return str(expr)
125
+
126
+ def _print_NumberSymbol(self, expr):
127
+ return str(expr)
128
+
129
+ def _print_Integer(self, expr):
130
+ return 'Integer(%i)' % expr.p
131
+
132
+ def _print_Complexes(self, expr):
133
+ return 'Complexes'
134
+
135
+ def _print_Integers(self, expr):
136
+ return 'Integers'
137
+
138
+ def _print_Naturals(self, expr):
139
+ return 'Naturals'
140
+
141
+ def _print_Naturals0(self, expr):
142
+ return 'Naturals0'
143
+
144
+ def _print_Rationals(self, expr):
145
+ return 'Rationals'
146
+
147
+ def _print_Reals(self, expr):
148
+ return 'Reals'
149
+
150
+ def _print_EmptySet(self, expr):
151
+ return 'EmptySet'
152
+
153
+ def _print_UniversalSet(self, expr):
154
+ return 'UniversalSet'
155
+
156
+ def _print_EmptySequence(self, expr):
157
+ return 'EmptySequence'
158
+
159
+ def _print_list(self, expr):
160
+ return "[%s]" % self.reprify(expr, ", ")
161
+
162
+ def _print_dict(self, expr):
163
+ sep = ", "
164
+ dict_kvs = ["%s: %s" % (self.doprint(key), self.doprint(value)) for key, value in expr.items()]
165
+ return "{%s}" % sep.join(dict_kvs)
166
+
167
+ def _print_set(self, expr):
168
+ if not expr:
169
+ return "set()"
170
+ return "{%s}" % self.reprify(expr, ", ")
171
+
172
+ def _print_MatrixBase(self, expr):
173
+ # special case for some empty matrices
174
+ if (expr.rows == 0) ^ (expr.cols == 0):
175
+ return '%s(%s, %s, %s)' % (expr.__class__.__name__,
176
+ self._print(expr.rows),
177
+ self._print(expr.cols),
178
+ self._print([]))
179
+ l = []
180
+ for i in range(expr.rows):
181
+ l.append([])
182
+ for j in range(expr.cols):
183
+ l[-1].append(expr[i, j])
184
+ return '%s(%s)' % (expr.__class__.__name__, self._print(l))
185
+
186
+ def _print_BooleanTrue(self, expr):
187
+ return "true"
188
+
189
+ def _print_BooleanFalse(self, expr):
190
+ return "false"
191
+
192
+ def _print_NaN(self, expr):
193
+ return "nan"
194
+
195
+ def _print_Mul(self, expr, order=None):
196
+ if self.order not in ('old', 'none'):
197
+ args = expr.as_ordered_factors()
198
+ else:
199
+ # use make_args in case expr was something like -x -> x
200
+ args = Mul.make_args(expr)
201
+
202
+ args = map(self._print, args)
203
+ clsname = type(expr).__name__
204
+ return clsname + "(%s)" % ", ".join(args)
205
+
206
+ def _print_Rational(self, expr):
207
+ return 'Rational(%s, %s)' % (self._print(expr.p), self._print(expr.q))
208
+
209
+ def _print_PythonRational(self, expr):
210
+ return "%s(%d, %d)" % (expr.__class__.__name__, expr.p, expr.q)
211
+
212
+ def _print_Fraction(self, expr):
213
+ return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator))
214
+
215
+ def _print_Float(self, expr):
216
+ r = mlib_to_str(expr._mpf_, repr_dps(expr._prec))
217
+ return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec)
218
+
219
+ def _print_Sum2(self, expr):
220
+ return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i),
221
+ self._print(expr.a), self._print(expr.b))
222
+
223
+ def _print_Str(self, s):
224
+ return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
225
+
226
+ def _print_Symbol(self, expr):
227
+ d = expr._assumptions_orig
228
+ # print the dummy_index like it was an assumption
229
+ if expr.is_Dummy:
230
+ d['dummy_index'] = expr.dummy_index
231
+
232
+ if d == {}:
233
+ return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))
234
+ else:
235
+ attr = ['%s=%s' % (k, v) for k, v in d.items()]
236
+ return "%s(%s, %s)" % (expr.__class__.__name__,
237
+ self._print(expr.name), ', '.join(attr))
238
+
239
+ def _print_CoordinateSymbol(self, expr):
240
+ d = expr._assumptions.generator
241
+
242
+ if d == {}:
243
+ return "%s(%s, %s)" % (
244
+ expr.__class__.__name__,
245
+ self._print(expr.coord_sys),
246
+ self._print(expr.index)
247
+ )
248
+ else:
249
+ attr = ['%s=%s' % (k, v) for k, v in d.items()]
250
+ return "%s(%s, %s, %s)" % (
251
+ expr.__class__.__name__,
252
+ self._print(expr.coord_sys),
253
+ self._print(expr.index),
254
+ ', '.join(attr)
255
+ )
256
+
257
+ def _print_Predicate(self, expr):
258
+ return "Q.%s" % expr.name
259
+
260
+ def _print_AppliedPredicate(self, expr):
261
+ # will be changed to just expr.args when args overriding is removed
262
+ args = expr._args
263
+ return "%s(%s)" % (expr.__class__.__name__, self.reprify(args, ", "))
264
+
265
+ def _print_str(self, expr):
266
+ return repr(expr)
267
+
268
+ def _print_tuple(self, expr):
269
+ if len(expr) == 1:
270
+ return "(%s,)" % self._print(expr[0])
271
+ else:
272
+ return "(%s)" % self.reprify(expr, ", ")
273
+
274
+ def _print_WildFunction(self, expr):
275
+ return "%s('%s')" % (expr.__class__.__name__, expr.name)
276
+
277
+ def _print_AlgebraicNumber(self, expr):
278
+ return "%s(%s, %s)" % (expr.__class__.__name__,
279
+ self._print(expr.root), self._print(expr.coeffs()))
280
+
281
+ def _print_PolyRing(self, ring):
282
+ return "%s(%s, %s, %s)" % (ring.__class__.__name__,
283
+ self._print(ring.symbols), self._print(ring.domain), self._print(ring.order))
284
+
285
+ def _print_FracField(self, field):
286
+ return "%s(%s, %s, %s)" % (field.__class__.__name__,
287
+ self._print(field.symbols), self._print(field.domain), self._print(field.order))
288
+
289
+ def _print_PolyElement(self, poly):
290
+ terms = list(poly.terms())
291
+ terms.sort(key=poly.ring.order, reverse=True)
292
+ return "%s(%s, %s)" % (poly.__class__.__name__, self._print(poly.ring), self._print(terms))
293
+
294
+ def _print_FracElement(self, frac):
295
+ numer_terms = list(frac.numer.terms())
296
+ numer_terms.sort(key=frac.field.order, reverse=True)
297
+ denom_terms = list(frac.denom.terms())
298
+ denom_terms.sort(key=frac.field.order, reverse=True)
299
+ numer = self._print(numer_terms)
300
+ denom = self._print(denom_terms)
301
+ return "%s(%s, %s, %s)" % (frac.__class__.__name__, self._print(frac.field), numer, denom)
302
+
303
+ def _print_FractionField(self, domain):
304
+ cls = domain.__class__.__name__
305
+ field = self._print(domain.field)
306
+ return "%s(%s)" % (cls, field)
307
+
308
+ def _print_PolynomialRingBase(self, ring):
309
+ cls = ring.__class__.__name__
310
+ dom = self._print(ring.domain)
311
+ gens = ', '.join(map(self._print, ring.gens))
312
+ order = str(ring.order)
313
+ if order != ring.default_order:
314
+ orderstr = ", order=" + order
315
+ else:
316
+ orderstr = ""
317
+ return "%s(%s, %s%s)" % (cls, dom, gens, orderstr)
318
+
319
+ def _print_DMP(self, p):
320
+ cls = p.__class__.__name__
321
+ rep = self._print(p.rep)
322
+ dom = self._print(p.dom)
323
+ if p.ring is not None:
324
+ ringstr = ", ring=" + self._print(p.ring)
325
+ else:
326
+ ringstr = ""
327
+ return "%s(%s, %s%s)" % (cls, rep, dom, ringstr)
328
+
329
+ def _print_MonogenicFiniteExtension(self, ext):
330
+ # The expanded tree shown by srepr(ext.modulus)
331
+ # is not practical.
332
+ return "FiniteExtension(%s)" % str(ext.modulus)
333
+
334
+ def _print_ExtensionElement(self, f):
335
+ rep = self._print(f.rep)
336
+ ext = self._print(f.ext)
337
+ return "ExtElem(%s, %s)" % (rep, ext)
338
+
339
+ @print_function(ReprPrinter)
340
+ def srepr(expr, **settings):
341
+ """return expr in repr form"""
342
+ return ReprPrinter(settings).doprint(expr)
env-llmeval/lib/python3.10/site-packages/sympy/printing/str.py ADDED
@@ -0,0 +1,1027 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Printer for generating readable representation of most SymPy classes.
3
+ """
4
+
5
+ from __future__ import annotations
6
+ from typing import Any
7
+
8
+ from sympy.core import S, Rational, Pow, Basic, Mul, Number
9
+ from sympy.core.mul import _keep_coeff
10
+ from sympy.core.relational import Relational
11
+ from sympy.core.sorting import default_sort_key
12
+ from sympy.core.sympify import SympifyError
13
+ from sympy.utilities.iterables import sift
14
+ from .precedence import precedence, PRECEDENCE
15
+ from .printer import Printer, print_function
16
+
17
+ from mpmath.libmp import prec_to_dps, to_str as mlib_to_str
18
+
19
+
20
+ class StrPrinter(Printer):
21
+ printmethod = "_sympystr"
22
+ _default_settings: dict[str, Any] = {
23
+ "order": None,
24
+ "full_prec": "auto",
25
+ "sympy_integers": False,
26
+ "abbrev": False,
27
+ "perm_cyclic": True,
28
+ "min": None,
29
+ "max": None,
30
+ }
31
+
32
+ _relationals: dict[str, str] = {}
33
+
34
+ def parenthesize(self, item, level, strict=False):
35
+ if (precedence(item) < level) or ((not strict) and precedence(item) <= level):
36
+ return "(%s)" % self._print(item)
37
+ else:
38
+ return self._print(item)
39
+
40
+ def stringify(self, args, sep, level=0):
41
+ return sep.join([self.parenthesize(item, level) for item in args])
42
+
43
+ def emptyPrinter(self, expr):
44
+ if isinstance(expr, str):
45
+ return expr
46
+ elif isinstance(expr, Basic):
47
+ return repr(expr)
48
+ else:
49
+ return str(expr)
50
+
51
+ def _print_Add(self, expr, order=None):
52
+ terms = self._as_ordered_terms(expr, order=order)
53
+
54
+ prec = precedence(expr)
55
+ l = []
56
+ for term in terms:
57
+ t = self._print(term)
58
+ if t.startswith('-') and not term.is_Add:
59
+ sign = "-"
60
+ t = t[1:]
61
+ else:
62
+ sign = "+"
63
+ if precedence(term) < prec or term.is_Add:
64
+ l.extend([sign, "(%s)" % t])
65
+ else:
66
+ l.extend([sign, t])
67
+ sign = l.pop(0)
68
+ if sign == '+':
69
+ sign = ""
70
+ return sign + ' '.join(l)
71
+
72
+ def _print_BooleanTrue(self, expr):
73
+ return "True"
74
+
75
+ def _print_BooleanFalse(self, expr):
76
+ return "False"
77
+
78
+ def _print_Not(self, expr):
79
+ return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"]))
80
+
81
+ def _print_And(self, expr):
82
+ args = list(expr.args)
83
+ for j, i in enumerate(args):
84
+ if isinstance(i, Relational) and (
85
+ i.canonical.rhs is S.NegativeInfinity):
86
+ args.insert(0, args.pop(j))
87
+ return self.stringify(args, " & ", PRECEDENCE["BitwiseAnd"])
88
+
89
+ def _print_Or(self, expr):
90
+ return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"])
91
+
92
+ def _print_Xor(self, expr):
93
+ return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"])
94
+
95
+ def _print_AppliedPredicate(self, expr):
96
+ return '%s(%s)' % (
97
+ self._print(expr.function), self.stringify(expr.arguments, ", "))
98
+
99
+ def _print_Basic(self, expr):
100
+ l = [self._print(o) for o in expr.args]
101
+ return expr.__class__.__name__ + "(%s)" % ", ".join(l)
102
+
103
+ def _print_BlockMatrix(self, B):
104
+ if B.blocks.shape == (1, 1):
105
+ self._print(B.blocks[0, 0])
106
+ return self._print(B.blocks)
107
+
108
+ def _print_Catalan(self, expr):
109
+ return 'Catalan'
110
+
111
+ def _print_ComplexInfinity(self, expr):
112
+ return 'zoo'
113
+
114
+ def _print_ConditionSet(self, s):
115
+ args = tuple([self._print(i) for i in (s.sym, s.condition)])
116
+ if s.base_set is S.UniversalSet:
117
+ return 'ConditionSet(%s, %s)' % args
118
+ args += (self._print(s.base_set),)
119
+ return 'ConditionSet(%s, %s, %s)' % args
120
+
121
+ def _print_Derivative(self, expr):
122
+ dexpr = expr.expr
123
+ dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]
124
+ return 'Derivative(%s)' % ", ".join((self._print(arg) for arg in [dexpr] + dvars))
125
+
126
+ def _print_dict(self, d):
127
+ keys = sorted(d.keys(), key=default_sort_key)
128
+ items = []
129
+
130
+ for key in keys:
131
+ item = "%s: %s" % (self._print(key), self._print(d[key]))
132
+ items.append(item)
133
+
134
+ return "{%s}" % ", ".join(items)
135
+
136
+ def _print_Dict(self, expr):
137
+ return self._print_dict(expr)
138
+
139
+ def _print_RandomDomain(self, d):
140
+ if hasattr(d, 'as_boolean'):
141
+ return 'Domain: ' + self._print(d.as_boolean())
142
+ elif hasattr(d, 'set'):
143
+ return ('Domain: ' + self._print(d.symbols) + ' in ' +
144
+ self._print(d.set))
145
+ else:
146
+ return 'Domain on ' + self._print(d.symbols)
147
+
148
+ def _print_Dummy(self, expr):
149
+ return '_' + expr.name
150
+
151
+ def _print_EulerGamma(self, expr):
152
+ return 'EulerGamma'
153
+
154
+ def _print_Exp1(self, expr):
155
+ return 'E'
156
+
157
+ def _print_ExprCondPair(self, expr):
158
+ return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond))
159
+
160
+ def _print_Function(self, expr):
161
+ return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ")
162
+
163
+ def _print_GoldenRatio(self, expr):
164
+ return 'GoldenRatio'
165
+
166
+ def _print_Heaviside(self, expr):
167
+ # Same as _print_Function but uses pargs to suppress default 1/2 for
168
+ # 2nd args
169
+ return expr.func.__name__ + "(%s)" % self.stringify(expr.pargs, ", ")
170
+
171
+ def _print_TribonacciConstant(self, expr):
172
+ return 'TribonacciConstant'
173
+
174
+ def _print_ImaginaryUnit(self, expr):
175
+ return 'I'
176
+
177
+ def _print_Infinity(self, expr):
178
+ return 'oo'
179
+
180
+ def _print_Integral(self, expr):
181
+ def _xab_tostr(xab):
182
+ if len(xab) == 1:
183
+ return self._print(xab[0])
184
+ else:
185
+ return self._print((xab[0],) + tuple(xab[1:]))
186
+ L = ', '.join([_xab_tostr(l) for l in expr.limits])
187
+ return 'Integral(%s, %s)' % (self._print(expr.function), L)
188
+
189
+ def _print_Interval(self, i):
190
+ fin = 'Interval{m}({a}, {b})'
191
+ a, b, l, r = i.args
192
+ if a.is_infinite and b.is_infinite:
193
+ m = ''
194
+ elif a.is_infinite and not r:
195
+ m = ''
196
+ elif b.is_infinite and not l:
197
+ m = ''
198
+ elif not l and not r:
199
+ m = ''
200
+ elif l and r:
201
+ m = '.open'
202
+ elif l:
203
+ m = '.Lopen'
204
+ else:
205
+ m = '.Ropen'
206
+ return fin.format(**{'a': a, 'b': b, 'm': m})
207
+
208
+ def _print_AccumulationBounds(self, i):
209
+ return "AccumBounds(%s, %s)" % (self._print(i.min),
210
+ self._print(i.max))
211
+
212
+ def _print_Inverse(self, I):
213
+ return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"])
214
+
215
+ def _print_Lambda(self, obj):
216
+ expr = obj.expr
217
+ sig = obj.signature
218
+ if len(sig) == 1 and sig[0].is_symbol:
219
+ sig = sig[0]
220
+ return "Lambda(%s, %s)" % (self._print(sig), self._print(expr))
221
+
222
+ def _print_LatticeOp(self, expr):
223
+ args = sorted(expr.args, key=default_sort_key)
224
+ return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args)
225
+
226
+ def _print_Limit(self, expr):
227
+ e, z, z0, dir = expr.args
228
+ return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir)))
229
+
230
+
231
+ def _print_list(self, expr):
232
+ return "[%s]" % self.stringify(expr, ", ")
233
+
234
+ def _print_List(self, expr):
235
+ return self._print_list(expr)
236
+
237
+ def _print_MatrixBase(self, expr):
238
+ return expr._format_str(self)
239
+
240
+ def _print_MatrixElement(self, expr):
241
+ return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
242
+ + '[%s, %s]' % (self._print(expr.i), self._print(expr.j))
243
+
244
+ def _print_MatrixSlice(self, expr):
245
+ def strslice(x, dim):
246
+ x = list(x)
247
+ if x[2] == 1:
248
+ del x[2]
249
+ if x[0] == 0:
250
+ x[0] = ''
251
+ if x[1] == dim:
252
+ x[1] = ''
253
+ return ':'.join((self._print(arg) for arg in x))
254
+ return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' +
255
+ strslice(expr.rowslice, expr.parent.rows) + ', ' +
256
+ strslice(expr.colslice, expr.parent.cols) + ']')
257
+
258
+ def _print_DeferredVector(self, expr):
259
+ return expr.name
260
+
261
+ def _print_Mul(self, expr):
262
+
263
+ prec = precedence(expr)
264
+
265
+ # Check for unevaluated Mul. In this case we need to make sure the
266
+ # identities are visible, multiple Rational factors are not combined
267
+ # etc so we display in a straight-forward form that fully preserves all
268
+ # args and their order.
269
+ args = expr.args
270
+ if args[0] is S.One or any(
271
+ isinstance(a, Number) or
272
+ a.is_Pow and all(ai.is_Integer for ai in a.args)
273
+ for a in args[1:]):
274
+ d, n = sift(args, lambda x:
275
+ isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0),
276
+ binary=True)
277
+ for i, di in enumerate(d):
278
+ if di.exp.is_Number:
279
+ e = -di.exp
280
+ else:
281
+ dargs = list(di.exp.args)
282
+ dargs[0] = -dargs[0]
283
+ e = Mul._from_args(dargs)
284
+ d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base
285
+
286
+ pre = []
287
+ # don't parenthesize first factor if negative
288
+ if n and not n[0].is_Add and n[0].could_extract_minus_sign():
289
+ pre = [self._print(n.pop(0))]
290
+
291
+ nfactors = pre + [self.parenthesize(a, prec, strict=False)
292
+ for a in n]
293
+ if not nfactors:
294
+ nfactors = ['1']
295
+
296
+ # don't parenthesize first of denominator unless singleton
297
+ if len(d) > 1 and d[0].could_extract_minus_sign():
298
+ pre = [self._print(d.pop(0))]
299
+ else:
300
+ pre = []
301
+ dfactors = pre + [self.parenthesize(a, prec, strict=False)
302
+ for a in d]
303
+
304
+ n = '*'.join(nfactors)
305
+ d = '*'.join(dfactors)
306
+ if len(dfactors) > 1:
307
+ return '%s/(%s)' % (n, d)
308
+ elif dfactors:
309
+ return '%s/%s' % (n, d)
310
+ return n
311
+
312
+ c, e = expr.as_coeff_Mul()
313
+ if c < 0:
314
+ expr = _keep_coeff(-c, e)
315
+ sign = "-"
316
+ else:
317
+ sign = ""
318
+
319
+ a = [] # items in the numerator
320
+ b = [] # items that are in the denominator (if any)
321
+
322
+ pow_paren = [] # Will collect all pow with more than one base element and exp = -1
323
+
324
+ if self.order not in ('old', 'none'):
325
+ args = expr.as_ordered_factors()
326
+ else:
327
+ # use make_args in case expr was something like -x -> x
328
+ args = Mul.make_args(expr)
329
+
330
+ # Gather args for numerator/denominator
331
+ def apow(i):
332
+ b, e = i.as_base_exp()
333
+ eargs = list(Mul.make_args(e))
334
+ if eargs[0] is S.NegativeOne:
335
+ eargs = eargs[1:]
336
+ else:
337
+ eargs[0] = -eargs[0]
338
+ e = Mul._from_args(eargs)
339
+ if isinstance(i, Pow):
340
+ return i.func(b, e, evaluate=False)
341
+ return i.func(e, evaluate=False)
342
+ for item in args:
343
+ if (item.is_commutative and
344
+ isinstance(item, Pow) and
345
+ bool(item.exp.as_coeff_Mul()[0] < 0)):
346
+ if item.exp is not S.NegativeOne:
347
+ b.append(apow(item))
348
+ else:
349
+ if (len(item.args[0].args) != 1 and
350
+ isinstance(item.base, (Mul, Pow))):
351
+ # To avoid situations like #14160
352
+ pow_paren.append(item)
353
+ b.append(item.base)
354
+ elif item.is_Rational and item is not S.Infinity:
355
+ if item.p != 1:
356
+ a.append(Rational(item.p))
357
+ if item.q != 1:
358
+ b.append(Rational(item.q))
359
+ else:
360
+ a.append(item)
361
+
362
+ a = a or [S.One]
363
+
364
+ a_str = [self.parenthesize(x, prec, strict=False) for x in a]
365
+ b_str = [self.parenthesize(x, prec, strict=False) for x in b]
366
+
367
+ # To parenthesize Pow with exp = -1 and having more than one Symbol
368
+ for item in pow_paren:
369
+ if item.base in b:
370
+ b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
371
+
372
+ if not b:
373
+ return sign + '*'.join(a_str)
374
+ elif len(b) == 1:
375
+ return sign + '*'.join(a_str) + "/" + b_str[0]
376
+ else:
377
+ return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
378
+
379
+ def _print_MatMul(self, expr):
380
+ c, m = expr.as_coeff_mmul()
381
+
382
+ sign = ""
383
+ if c.is_number:
384
+ re, im = c.as_real_imag()
385
+ if im.is_zero and re.is_negative:
386
+ expr = _keep_coeff(-c, m)
387
+ sign = "-"
388
+ elif re.is_zero and im.is_negative:
389
+ expr = _keep_coeff(-c, m)
390
+ sign = "-"
391
+
392
+ return sign + '*'.join(
393
+ [self.parenthesize(arg, precedence(expr)) for arg in expr.args]
394
+ )
395
+
396
+ def _print_ElementwiseApplyFunction(self, expr):
397
+ return "{}.({})".format(
398
+ expr.function,
399
+ self._print(expr.expr),
400
+ )
401
+
402
+ def _print_NaN(self, expr):
403
+ return 'nan'
404
+
405
+ def _print_NegativeInfinity(self, expr):
406
+ return '-oo'
407
+
408
+ def _print_Order(self, expr):
409
+ if not expr.variables or all(p is S.Zero for p in expr.point):
410
+ if len(expr.variables) <= 1:
411
+ return 'O(%s)' % self._print(expr.expr)
412
+ else:
413
+ return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0)
414
+ else:
415
+ return 'O(%s)' % self.stringify(expr.args, ', ', 0)
416
+
417
+ def _print_Ordinal(self, expr):
418
+ return expr.__str__()
419
+
420
+ def _print_Cycle(self, expr):
421
+ return expr.__str__()
422
+
423
+ def _print_Permutation(self, expr):
424
+ from sympy.combinatorics.permutations import Permutation, Cycle
425
+ from sympy.utilities.exceptions import sympy_deprecation_warning
426
+
427
+ perm_cyclic = Permutation.print_cyclic
428
+ if perm_cyclic is not None:
429
+ sympy_deprecation_warning(
430
+ f"""
431
+ Setting Permutation.print_cyclic is deprecated. Instead use
432
+ init_printing(perm_cyclic={perm_cyclic}).
433
+ """,
434
+ deprecated_since_version="1.6",
435
+ active_deprecations_target="deprecated-permutation-print_cyclic",
436
+ stacklevel=7,
437
+ )
438
+ else:
439
+ perm_cyclic = self._settings.get("perm_cyclic", True)
440
+
441
+ if perm_cyclic:
442
+ if not expr.size:
443
+ return '()'
444
+ # before taking Cycle notation, see if the last element is
445
+ # a singleton and move it to the head of the string
446
+ s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):]
447
+ last = s.rfind('(')
448
+ if not last == 0 and ',' not in s[last:]:
449
+ s = s[last:] + s[:last]
450
+ s = s.replace(',', '')
451
+ return s
452
+ else:
453
+ s = expr.support()
454
+ if not s:
455
+ if expr.size < 5:
456
+ return 'Permutation(%s)' % self._print(expr.array_form)
457
+ return 'Permutation([], size=%s)' % self._print(expr.size)
458
+ trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size)
459
+ use = full = self._print(expr.array_form)
460
+ if len(trim) < len(full):
461
+ use = trim
462
+ return 'Permutation(%s)' % use
463
+
464
+ def _print_Subs(self, obj):
465
+ expr, old, new = obj.args
466
+ if len(obj.point) == 1:
467
+ old = old[0]
468
+ new = new[0]
469
+ return "Subs(%s, %s, %s)" % (
470
+ self._print(expr), self._print(old), self._print(new))
471
+
472
+ def _print_TensorIndex(self, expr):
473
+ return expr._print()
474
+
475
+ def _print_TensorHead(self, expr):
476
+ return expr._print()
477
+
478
+ def _print_Tensor(self, expr):
479
+ return expr._print()
480
+
481
+ def _print_TensMul(self, expr):
482
+ # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
483
+ sign, args = expr._get_args_for_traditional_printer()
484
+ return sign + "*".join(
485
+ [self.parenthesize(arg, precedence(expr)) for arg in args]
486
+ )
487
+
488
+ def _print_TensAdd(self, expr):
489
+ return expr._print()
490
+
491
+ def _print_ArraySymbol(self, expr):
492
+ return self._print(expr.name)
493
+
494
+ def _print_ArrayElement(self, expr):
495
+ return "%s[%s]" % (
496
+ self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([self._print(i) for i in expr.indices]))
497
+
498
+ def _print_PermutationGroup(self, expr):
499
+ p = [' %s' % self._print(a) for a in expr.args]
500
+ return 'PermutationGroup([\n%s])' % ',\n'.join(p)
501
+
502
+ def _print_Pi(self, expr):
503
+ return 'pi'
504
+
505
+ def _print_PolyRing(self, ring):
506
+ return "Polynomial ring in %s over %s with %s order" % \
507
+ (", ".join((self._print(rs) for rs in ring.symbols)),
508
+ self._print(ring.domain), self._print(ring.order))
509
+
510
+ def _print_FracField(self, field):
511
+ return "Rational function field in %s over %s with %s order" % \
512
+ (", ".join((self._print(fs) for fs in field.symbols)),
513
+ self._print(field.domain), self._print(field.order))
514
+
515
+ def _print_FreeGroupElement(self, elm):
516
+ return elm.__str__()
517
+
518
+ def _print_GaussianElement(self, poly):
519
+ return "(%s + %s*I)" % (poly.x, poly.y)
520
+
521
+ def _print_PolyElement(self, poly):
522
+ return poly.str(self, PRECEDENCE, "%s**%s", "*")
523
+
524
+ def _print_FracElement(self, frac):
525
+ if frac.denom == 1:
526
+ return self._print(frac.numer)
527
+ else:
528
+ numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True)
529
+ denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True)
530
+ return numer + "/" + denom
531
+
532
+ def _print_Poly(self, expr):
533
+ ATOM_PREC = PRECEDENCE["Atom"] - 1
534
+ terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ]
535
+
536
+ for monom, coeff in expr.terms():
537
+ s_monom = []
538
+
539
+ for i, e in enumerate(monom):
540
+ if e > 0:
541
+ if e == 1:
542
+ s_monom.append(gens[i])
543
+ else:
544
+ s_monom.append(gens[i] + "**%d" % e)
545
+
546
+ s_monom = "*".join(s_monom)
547
+
548
+ if coeff.is_Add:
549
+ if s_monom:
550
+ s_coeff = "(" + self._print(coeff) + ")"
551
+ else:
552
+ s_coeff = self._print(coeff)
553
+ else:
554
+ if s_monom:
555
+ if coeff is S.One:
556
+ terms.extend(['+', s_monom])
557
+ continue
558
+
559
+ if coeff is S.NegativeOne:
560
+ terms.extend(['-', s_monom])
561
+ continue
562
+
563
+ s_coeff = self._print(coeff)
564
+
565
+ if not s_monom:
566
+ s_term = s_coeff
567
+ else:
568
+ s_term = s_coeff + "*" + s_monom
569
+
570
+ if s_term.startswith('-'):
571
+ terms.extend(['-', s_term[1:]])
572
+ else:
573
+ terms.extend(['+', s_term])
574
+
575
+ if terms[0] in ('-', '+'):
576
+ modifier = terms.pop(0)
577
+
578
+ if modifier == '-':
579
+ terms[0] = '-' + terms[0]
580
+
581
+ format = expr.__class__.__name__ + "(%s, %s"
582
+
583
+ from sympy.polys.polyerrors import PolynomialError
584
+
585
+ try:
586
+ format += ", modulus=%s" % expr.get_modulus()
587
+ except PolynomialError:
588
+ format += ", domain='%s'" % expr.get_domain()
589
+
590
+ format += ")"
591
+
592
+ for index, item in enumerate(gens):
593
+ if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"):
594
+ gens[index] = item[1:len(item) - 1]
595
+
596
+ return format % (' '.join(terms), ', '.join(gens))
597
+
598
+ def _print_UniversalSet(self, p):
599
+ return 'UniversalSet'
600
+
601
+ def _print_AlgebraicNumber(self, expr):
602
+ if expr.is_aliased:
603
+ return self._print(expr.as_poly().as_expr())
604
+ else:
605
+ return self._print(expr.as_expr())
606
+
607
+ def _print_Pow(self, expr, rational=False):
608
+ """Printing helper function for ``Pow``
609
+
610
+ Parameters
611
+ ==========
612
+
613
+ rational : bool, optional
614
+ If ``True``, it will not attempt printing ``sqrt(x)`` or
615
+ ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)``
616
+ instead.
617
+
618
+ See examples for additional details
619
+
620
+ Examples
621
+ ========
622
+
623
+ >>> from sympy import sqrt, StrPrinter
624
+ >>> from sympy.abc import x
625
+
626
+ How ``rational`` keyword works with ``sqrt``:
627
+
628
+ >>> printer = StrPrinter()
629
+ >>> printer._print_Pow(sqrt(x), rational=True)
630
+ 'x**(1/2)'
631
+ >>> printer._print_Pow(sqrt(x), rational=False)
632
+ 'sqrt(x)'
633
+ >>> printer._print_Pow(1/sqrt(x), rational=True)
634
+ 'x**(-1/2)'
635
+ >>> printer._print_Pow(1/sqrt(x), rational=False)
636
+ '1/sqrt(x)'
637
+
638
+ Notes
639
+ =====
640
+
641
+ ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy,
642
+ so there is no need of defining a separate printer for ``sqrt``.
643
+ Instead, it should be handled here as well.
644
+ """
645
+ PREC = precedence(expr)
646
+
647
+ if expr.exp is S.Half and not rational:
648
+ return "sqrt(%s)" % self._print(expr.base)
649
+
650
+ if expr.is_commutative:
651
+ if -expr.exp is S.Half and not rational:
652
+ # Note: Don't test "expr.exp == -S.Half" here, because that will
653
+ # match -0.5, which we don't want.
654
+ return "%s/sqrt(%s)" % tuple((self._print(arg) for arg in (S.One, expr.base)))
655
+ if expr.exp is -S.One:
656
+ # Similarly to the S.Half case, don't test with "==" here.
657
+ return '%s/%s' % (self._print(S.One),
658
+ self.parenthesize(expr.base, PREC, strict=False))
659
+
660
+ e = self.parenthesize(expr.exp, PREC, strict=False)
661
+ if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1:
662
+ # the parenthesized exp should be '(Rational(a, b))' so strip parens,
663
+ # but just check to be sure.
664
+ if e.startswith('(Rational'):
665
+ return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1])
666
+ return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e)
667
+
668
+ def _print_UnevaluatedExpr(self, expr):
669
+ return self._print(expr.args[0])
670
+
671
+ def _print_MatPow(self, expr):
672
+ PREC = precedence(expr)
673
+ return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False),
674
+ self.parenthesize(expr.exp, PREC, strict=False))
675
+
676
+ def _print_Integer(self, expr):
677
+ if self._settings.get("sympy_integers", False):
678
+ return "S(%s)" % (expr)
679
+ return str(expr.p)
680
+
681
+ def _print_Integers(self, expr):
682
+ return 'Integers'
683
+
684
+ def _print_Naturals(self, expr):
685
+ return 'Naturals'
686
+
687
+ def _print_Naturals0(self, expr):
688
+ return 'Naturals0'
689
+
690
+ def _print_Rationals(self, expr):
691
+ return 'Rationals'
692
+
693
+ def _print_Reals(self, expr):
694
+ return 'Reals'
695
+
696
+ def _print_Complexes(self, expr):
697
+ return 'Complexes'
698
+
699
+ def _print_EmptySet(self, expr):
700
+ return 'EmptySet'
701
+
702
+ def _print_EmptySequence(self, expr):
703
+ return 'EmptySequence'
704
+
705
+ def _print_int(self, expr):
706
+ return str(expr)
707
+
708
+ def _print_mpz(self, expr):
709
+ return str(expr)
710
+
711
+ def _print_Rational(self, expr):
712
+ if expr.q == 1:
713
+ return str(expr.p)
714
+ else:
715
+ if self._settings.get("sympy_integers", False):
716
+ return "S(%s)/%s" % (expr.p, expr.q)
717
+ return "%s/%s" % (expr.p, expr.q)
718
+
719
+ def _print_PythonRational(self, expr):
720
+ if expr.q == 1:
721
+ return str(expr.p)
722
+ else:
723
+ return "%d/%d" % (expr.p, expr.q)
724
+
725
+ def _print_Fraction(self, expr):
726
+ if expr.denominator == 1:
727
+ return str(expr.numerator)
728
+ else:
729
+ return "%s/%s" % (expr.numerator, expr.denominator)
730
+
731
+ def _print_mpq(self, expr):
732
+ if expr.denominator == 1:
733
+ return str(expr.numerator)
734
+ else:
735
+ return "%s/%s" % (expr.numerator, expr.denominator)
736
+
737
+ def _print_Float(self, expr):
738
+ prec = expr._prec
739
+ if prec < 5:
740
+ dps = 0
741
+ else:
742
+ dps = prec_to_dps(expr._prec)
743
+ if self._settings["full_prec"] is True:
744
+ strip = False
745
+ elif self._settings["full_prec"] is False:
746
+ strip = True
747
+ elif self._settings["full_prec"] == "auto":
748
+ strip = self._print_level > 1
749
+ low = self._settings["min"] if "min" in self._settings else None
750
+ high = self._settings["max"] if "max" in self._settings else None
751
+ rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high)
752
+ if rv.startswith('-.0'):
753
+ rv = '-0.' + rv[3:]
754
+ elif rv.startswith('.0'):
755
+ rv = '0.' + rv[2:]
756
+ if rv.startswith('+'):
757
+ # e.g., +inf -> inf
758
+ rv = rv[1:]
759
+ return rv
760
+
761
+ def _print_Relational(self, expr):
762
+
763
+ charmap = {
764
+ "==": "Eq",
765
+ "!=": "Ne",
766
+ ":=": "Assignment",
767
+ '+=': "AddAugmentedAssignment",
768
+ "-=": "SubAugmentedAssignment",
769
+ "*=": "MulAugmentedAssignment",
770
+ "/=": "DivAugmentedAssignment",
771
+ "%=": "ModAugmentedAssignment",
772
+ }
773
+
774
+ if expr.rel_op in charmap:
775
+ return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs),
776
+ self._print(expr.rhs))
777
+
778
+ return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)),
779
+ self._relationals.get(expr.rel_op) or expr.rel_op,
780
+ self.parenthesize(expr.rhs, precedence(expr)))
781
+
782
+ def _print_ComplexRootOf(self, expr):
783
+ return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'),
784
+ expr.index)
785
+
786
+ def _print_RootSum(self, expr):
787
+ args = [self._print_Add(expr.expr, order='lex')]
788
+
789
+ if expr.fun is not S.IdentityFunction:
790
+ args.append(self._print(expr.fun))
791
+
792
+ return "RootSum(%s)" % ", ".join(args)
793
+
794
+ def _print_GroebnerBasis(self, basis):
795
+ cls = basis.__class__.__name__
796
+
797
+ exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs]
798
+ exprs = "[%s]" % ", ".join(exprs)
799
+
800
+ gens = [ self._print(gen) for gen in basis.gens ]
801
+ domain = "domain='%s'" % self._print(basis.domain)
802
+ order = "order='%s'" % self._print(basis.order)
803
+
804
+ args = [exprs] + gens + [domain, order]
805
+
806
+ return "%s(%s)" % (cls, ", ".join(args))
807
+
808
+ def _print_set(self, s):
809
+ items = sorted(s, key=default_sort_key)
810
+
811
+ args = ', '.join(self._print(item) for item in items)
812
+ if not args:
813
+ return "set()"
814
+ return '{%s}' % args
815
+
816
+ def _print_FiniteSet(self, s):
817
+ from sympy.sets.sets import FiniteSet
818
+ items = sorted(s, key=default_sort_key)
819
+
820
+ args = ', '.join(self._print(item) for item in items)
821
+ if any(item.has(FiniteSet) for item in items):
822
+ return 'FiniteSet({})'.format(args)
823
+ return '{{{}}}'.format(args)
824
+
825
+ def _print_Partition(self, s):
826
+ items = sorted(s, key=default_sort_key)
827
+
828
+ args = ', '.join(self._print(arg) for arg in items)
829
+ return 'Partition({})'.format(args)
830
+
831
+ def _print_frozenset(self, s):
832
+ if not s:
833
+ return "frozenset()"
834
+ return "frozenset(%s)" % self._print_set(s)
835
+
836
+ def _print_Sum(self, expr):
837
+ def _xab_tostr(xab):
838
+ if len(xab) == 1:
839
+ return self._print(xab[0])
840
+ else:
841
+ return self._print((xab[0],) + tuple(xab[1:]))
842
+ L = ', '.join([_xab_tostr(l) for l in expr.limits])
843
+ return 'Sum(%s, %s)' % (self._print(expr.function), L)
844
+
845
+ def _print_Symbol(self, expr):
846
+ return expr.name
847
+ _print_MatrixSymbol = _print_Symbol
848
+ _print_RandomSymbol = _print_Symbol
849
+
850
+ def _print_Identity(self, expr):
851
+ return "I"
852
+
853
+ def _print_ZeroMatrix(self, expr):
854
+ return "0"
855
+
856
+ def _print_OneMatrix(self, expr):
857
+ return "1"
858
+
859
+ def _print_Predicate(self, expr):
860
+ return "Q.%s" % expr.name
861
+
862
+ def _print_str(self, expr):
863
+ return str(expr)
864
+
865
+ def _print_tuple(self, expr):
866
+ if len(expr) == 1:
867
+ return "(%s,)" % self._print(expr[0])
868
+ else:
869
+ return "(%s)" % self.stringify(expr, ", ")
870
+
871
+ def _print_Tuple(self, expr):
872
+ return self._print_tuple(expr)
873
+
874
+ def _print_Transpose(self, T):
875
+ return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"])
876
+
877
+ def _print_Uniform(self, expr):
878
+ return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b))
879
+
880
+ def _print_Quantity(self, expr):
881
+ if self._settings.get("abbrev", False):
882
+ return "%s" % expr.abbrev
883
+ return "%s" % expr.name
884
+
885
+ def _print_Quaternion(self, expr):
886
+ s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args]
887
+ a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")]
888
+ return " + ".join(a)
889
+
890
+ def _print_Dimension(self, expr):
891
+ return str(expr)
892
+
893
+ def _print_Wild(self, expr):
894
+ return expr.name + '_'
895
+
896
+ def _print_WildFunction(self, expr):
897
+ return expr.name + '_'
898
+
899
+ def _print_WildDot(self, expr):
900
+ return expr.name
901
+
902
+ def _print_WildPlus(self, expr):
903
+ return expr.name
904
+
905
+ def _print_WildStar(self, expr):
906
+ return expr.name
907
+
908
+ def _print_Zero(self, expr):
909
+ if self._settings.get("sympy_integers", False):
910
+ return "S(0)"
911
+ return "0"
912
+
913
+ def _print_DMP(self, p):
914
+ try:
915
+ if p.ring is not None:
916
+ # TODO incorporate order
917
+ return self._print(p.ring.to_sympy(p))
918
+ except SympifyError:
919
+ pass
920
+
921
+ cls = p.__class__.__name__
922
+ rep = self._print(p.rep)
923
+ dom = self._print(p.dom)
924
+ ring = self._print(p.ring)
925
+
926
+ return "%s(%s, %s, %s)" % (cls, rep, dom, ring)
927
+
928
+ def _print_DMF(self, expr):
929
+ return self._print_DMP(expr)
930
+
931
+ def _print_Object(self, obj):
932
+ return 'Object("%s")' % obj.name
933
+
934
+ def _print_IdentityMorphism(self, morphism):
935
+ return 'IdentityMorphism(%s)' % morphism.domain
936
+
937
+ def _print_NamedMorphism(self, morphism):
938
+ return 'NamedMorphism(%s, %s, "%s")' % \
939
+ (morphism.domain, morphism.codomain, morphism.name)
940
+
941
+ def _print_Category(self, category):
942
+ return 'Category("%s")' % category.name
943
+
944
+ def _print_Manifold(self, manifold):
945
+ return manifold.name.name
946
+
947
+ def _print_Patch(self, patch):
948
+ return patch.name.name
949
+
950
+ def _print_CoordSystem(self, coords):
951
+ return coords.name.name
952
+
953
+ def _print_BaseScalarField(self, field):
954
+ return field._coord_sys.symbols[field._index].name
955
+
956
+ def _print_BaseVectorField(self, field):
957
+ return 'e_%s' % field._coord_sys.symbols[field._index].name
958
+
959
+ def _print_Differential(self, diff):
960
+ field = diff._form_field
961
+ if hasattr(field, '_coord_sys'):
962
+ return 'd%s' % field._coord_sys.symbols[field._index].name
963
+ else:
964
+ return 'd(%s)' % self._print(field)
965
+
966
+ def _print_Tr(self, expr):
967
+ #TODO : Handle indices
968
+ return "%s(%s)" % ("Tr", self._print(expr.args[0]))
969
+
970
+ def _print_Str(self, s):
971
+ return self._print(s.name)
972
+
973
+ def _print_AppliedBinaryRelation(self, expr):
974
+ rel = expr.function
975
+ return '%s(%s, %s)' % (self._print(rel),
976
+ self._print(expr.lhs),
977
+ self._print(expr.rhs))
978
+
979
+
980
+ @print_function(StrPrinter)
981
+ def sstr(expr, **settings):
982
+ """Returns the expression as a string.
983
+
984
+ For large expressions where speed is a concern, use the setting
985
+ order='none'. If abbrev=True setting is used then units are printed in
986
+ abbreviated form.
987
+
988
+ Examples
989
+ ========
990
+
991
+ >>> from sympy import symbols, Eq, sstr
992
+ >>> a, b = symbols('a b')
993
+ >>> sstr(Eq(a + b, 0))
994
+ 'Eq(a + b, 0)'
995
+ """
996
+
997
+ p = StrPrinter(settings)
998
+ s = p.doprint(expr)
999
+
1000
+ return s
1001
+
1002
+
1003
+ class StrReprPrinter(StrPrinter):
1004
+ """(internal) -- see sstrrepr"""
1005
+
1006
+ def _print_str(self, s):
1007
+ return repr(s)
1008
+
1009
+ def _print_Str(self, s):
1010
+ # Str does not to be printed same as str here
1011
+ return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
1012
+
1013
+
1014
+ @print_function(StrReprPrinter)
1015
+ def sstrrepr(expr, **settings):
1016
+ """return expr in mixed str/repr form
1017
+
1018
+ i.e. strings are returned in repr form with quotes, and everything else
1019
+ is returned in str form.
1020
+
1021
+ This function could be useful for hooking into sys.displayhook
1022
+ """
1023
+
1024
+ p = StrReprPrinter(settings)
1025
+ s = p.doprint(expr)
1026
+
1027
+ return s
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_aesaracode.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Important note on tests in this module - the Aesara printing functions use a
3
+ global cache by default, which means that tests using it will modify global
4
+ state and thus not be independent from each other. Instead of using the "cache"
5
+ keyword argument each time, this module uses the aesara_code_ and
6
+ aesara_function_ functions defined below which default to using a new, empty
7
+ cache instead.
8
+ """
9
+
10
+ import logging
11
+
12
+ from sympy.external import import_module
13
+ from sympy.testing.pytest import raises, SKIP
14
+
15
+ from sympy.utilities.exceptions import ignore_warnings
16
+
17
+
18
+ aesaralogger = logging.getLogger('aesara.configdefaults')
19
+ aesaralogger.setLevel(logging.CRITICAL)
20
+ aesara = import_module('aesara')
21
+ aesaralogger.setLevel(logging.WARNING)
22
+
23
+
24
+ if aesara:
25
+ import numpy as np
26
+ aet = aesara.tensor
27
+ from aesara.scalar.basic import Scalar
28
+ from aesara.graph.basic import Variable
29
+ from aesara.tensor.var import TensorVariable
30
+ from aesara.tensor.elemwise import Elemwise, DimShuffle
31
+ from aesara.tensor.math import Dot
32
+
33
+ from sympy.printing.aesaracode import true_divide
34
+
35
+ xt, yt, zt = [aet.scalar(name, 'floatX') for name in 'xyz']
36
+ Xt, Yt, Zt = [aet.tensor('floatX', (False, False), name=n) for n in 'XYZ']
37
+ else:
38
+ #bin/test will not execute any tests now
39
+ disabled = True
40
+
41
+ import sympy as sy
42
+ from sympy.core.singleton import S
43
+ from sympy.abc import x, y, z, t
44
+ from sympy.printing.aesaracode import (aesara_code, dim_handling,
45
+ aesara_function)
46
+
47
+
48
+ # Default set of matrix symbols for testing - make square so we can both
49
+ # multiply and perform elementwise operations between them.
50
+ X, Y, Z = [sy.MatrixSymbol(n, 4, 4) for n in 'XYZ']
51
+
52
+ # For testing AppliedUndef
53
+ f_t = sy.Function('f')(t)
54
+
55
+
56
+ def aesara_code_(expr, **kwargs):
57
+ """ Wrapper for aesara_code that uses a new, empty cache by default. """
58
+ kwargs.setdefault('cache', {})
59
+ return aesara_code(expr, **kwargs)
60
+
61
+ def aesara_function_(inputs, outputs, **kwargs):
62
+ """ Wrapper for aesara_function that uses a new, empty cache by default. """
63
+ kwargs.setdefault('cache', {})
64
+ return aesara_function(inputs, outputs, **kwargs)
65
+
66
+
67
+ def fgraph_of(*exprs):
68
+ """ Transform SymPy expressions into Aesara Computation.
69
+
70
+ Parameters
71
+ ==========
72
+ exprs
73
+ SymPy expressions
74
+
75
+ Returns
76
+ =======
77
+ aesara.graph.fg.FunctionGraph
78
+ """
79
+ outs = list(map(aesara_code_, exprs))
80
+ ins = list(aesara.graph.basic.graph_inputs(outs))
81
+ ins, outs = aesara.graph.basic.clone(ins, outs)
82
+ return aesara.graph.fg.FunctionGraph(ins, outs)
83
+
84
+
85
+ def aesara_simplify(fgraph):
86
+ """ Simplify a Aesara Computation.
87
+
88
+ Parameters
89
+ ==========
90
+ fgraph : aesara.graph.fg.FunctionGraph
91
+
92
+ Returns
93
+ =======
94
+ aesara.graph.fg.FunctionGraph
95
+ """
96
+ mode = aesara.compile.get_default_mode().excluding("fusion")
97
+ fgraph = fgraph.clone()
98
+ mode.optimizer.optimize(fgraph)
99
+ return fgraph
100
+
101
+
102
+ def theq(a, b):
103
+ """ Test two Aesara objects for equality.
104
+
105
+ Also accepts numeric types and lists/tuples of supported types.
106
+
107
+ Note - debugprint() has a bug where it will accept numeric types but does
108
+ not respect the "file" argument and in this case and instead prints the number
109
+ to stdout and returns an empty string. This can lead to tests passing where
110
+ they should fail because any two numbers will always compare as equal. To
111
+ prevent this we treat numbers as a separate case.
112
+ """
113
+ numeric_types = (int, float, np.number)
114
+ a_is_num = isinstance(a, numeric_types)
115
+ b_is_num = isinstance(b, numeric_types)
116
+
117
+ # Compare numeric types using regular equality
118
+ if a_is_num or b_is_num:
119
+ if not (a_is_num and b_is_num):
120
+ return False
121
+
122
+ return a == b
123
+
124
+ # Compare sequences element-wise
125
+ a_is_seq = isinstance(a, (tuple, list))
126
+ b_is_seq = isinstance(b, (tuple, list))
127
+
128
+ if a_is_seq or b_is_seq:
129
+ if not (a_is_seq and b_is_seq) or type(a) != type(b):
130
+ return False
131
+
132
+ return list(map(theq, a)) == list(map(theq, b))
133
+
134
+ # Otherwise, assume debugprint() can handle it
135
+ astr = aesara.printing.debugprint(a, file='str')
136
+ bstr = aesara.printing.debugprint(b, file='str')
137
+
138
+ # Check for bug mentioned above
139
+ for argname, argval, argstr in [('a', a, astr), ('b', b, bstr)]:
140
+ if argstr == '':
141
+ raise TypeError(
142
+ 'aesara.printing.debugprint(%s) returned empty string '
143
+ '(%s is instance of %r)'
144
+ % (argname, argname, type(argval))
145
+ )
146
+
147
+ return astr == bstr
148
+
149
+
150
+ def test_example_symbols():
151
+ """
152
+ Check that the example symbols in this module print to their Aesara
153
+ equivalents, as many of the other tests depend on this.
154
+ """
155
+ assert theq(xt, aesara_code_(x))
156
+ assert theq(yt, aesara_code_(y))
157
+ assert theq(zt, aesara_code_(z))
158
+ assert theq(Xt, aesara_code_(X))
159
+ assert theq(Yt, aesara_code_(Y))
160
+ assert theq(Zt, aesara_code_(Z))
161
+
162
+
163
+ def test_Symbol():
164
+ """ Test printing a Symbol to a aesara variable. """
165
+ xx = aesara_code_(x)
166
+ assert isinstance(xx, Variable)
167
+ assert xx.broadcastable == ()
168
+ assert xx.name == x.name
169
+
170
+ xx2 = aesara_code_(x, broadcastables={x: (False,)})
171
+ assert xx2.broadcastable == (False,)
172
+ assert xx2.name == x.name
173
+
174
+ def test_MatrixSymbol():
175
+ """ Test printing a MatrixSymbol to a aesara variable. """
176
+ XX = aesara_code_(X)
177
+ assert isinstance(XX, TensorVariable)
178
+ assert XX.broadcastable == (False, False)
179
+
180
+ @SKIP # TODO - this is currently not checked but should be implemented
181
+ def test_MatrixSymbol_wrong_dims():
182
+ """ Test MatrixSymbol with invalid broadcastable. """
183
+ bcs = [(), (False,), (True,), (True, False), (False, True,), (True, True)]
184
+ for bc in bcs:
185
+ with raises(ValueError):
186
+ aesara_code_(X, broadcastables={X: bc})
187
+
188
+ def test_AppliedUndef():
189
+ """ Test printing AppliedUndef instance, which works similarly to Symbol. """
190
+ ftt = aesara_code_(f_t)
191
+ assert isinstance(ftt, TensorVariable)
192
+ assert ftt.broadcastable == ()
193
+ assert ftt.name == 'f_t'
194
+
195
+
196
+ def test_add():
197
+ expr = x + y
198
+ comp = aesara_code_(expr)
199
+ assert comp.owner.op == aesara.tensor.add
200
+
201
+ def test_trig():
202
+ assert theq(aesara_code_(sy.sin(x)), aet.sin(xt))
203
+ assert theq(aesara_code_(sy.tan(x)), aet.tan(xt))
204
+
205
+ def test_many():
206
+ """ Test printing a complex expression with multiple symbols. """
207
+ expr = sy.exp(x**2 + sy.cos(y)) * sy.log(2*z)
208
+ comp = aesara_code_(expr)
209
+ expected = aet.exp(xt**2 + aet.cos(yt)) * aet.log(2*zt)
210
+ assert theq(comp, expected)
211
+
212
+
213
+ def test_dtype():
214
+ """ Test specifying specific data types through the dtype argument. """
215
+ for dtype in ['float32', 'float64', 'int8', 'int16', 'int32', 'int64']:
216
+ assert aesara_code_(x, dtypes={x: dtype}).type.dtype == dtype
217
+
218
+ # "floatX" type
219
+ assert aesara_code_(x, dtypes={x: 'floatX'}).type.dtype in ('float32', 'float64')
220
+
221
+ # Type promotion
222
+ assert aesara_code_(x + 1, dtypes={x: 'float32'}).type.dtype == 'float32'
223
+ assert aesara_code_(x + y, dtypes={x: 'float64', y: 'float32'}).type.dtype == 'float64'
224
+
225
+
226
+ def test_broadcastables():
227
+ """ Test the "broadcastables" argument when printing symbol-like objects. """
228
+
229
+ # No restrictions on shape
230
+ for s in [x, f_t]:
231
+ for bc in [(), (False,), (True,), (False, False), (True, False)]:
232
+ assert aesara_code_(s, broadcastables={s: bc}).broadcastable == bc
233
+
234
+ # TODO - matrix broadcasting?
235
+
236
+ def test_broadcasting():
237
+ """ Test "broadcastable" attribute after applying element-wise binary op. """
238
+
239
+ expr = x + y
240
+
241
+ cases = [
242
+ [(), (), ()],
243
+ [(False,), (False,), (False,)],
244
+ [(True,), (False,), (False,)],
245
+ [(False, True), (False, False), (False, False)],
246
+ [(True, False), (False, False), (False, False)],
247
+ ]
248
+
249
+ for bc1, bc2, bc3 in cases:
250
+ comp = aesara_code_(expr, broadcastables={x: bc1, y: bc2})
251
+ assert comp.broadcastable == bc3
252
+
253
+
254
+ def test_MatMul():
255
+ expr = X*Y*Z
256
+ expr_t = aesara_code_(expr)
257
+ assert isinstance(expr_t.owner.op, Dot)
258
+ assert theq(expr_t, Xt.dot(Yt).dot(Zt))
259
+
260
+ def test_Transpose():
261
+ assert isinstance(aesara_code_(X.T).owner.op, DimShuffle)
262
+
263
+ def test_MatAdd():
264
+ expr = X+Y+Z
265
+ assert isinstance(aesara_code_(expr).owner.op, Elemwise)
266
+
267
+
268
+ def test_Rationals():
269
+ assert theq(aesara_code_(sy.Integer(2) / 3), true_divide(2, 3))
270
+ assert theq(aesara_code_(S.Half), true_divide(1, 2))
271
+
272
+ def test_Integers():
273
+ assert aesara_code_(sy.Integer(3)) == 3
274
+
275
+ def test_factorial():
276
+ n = sy.Symbol('n')
277
+ assert aesara_code_(sy.factorial(n))
278
+
279
+ def test_Derivative():
280
+ with ignore_warnings(UserWarning):
281
+ simp = lambda expr: aesara_simplify(fgraph_of(expr))
282
+ assert theq(simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
283
+ simp(aesara.grad(aet.sin(xt), xt)))
284
+
285
+
286
+ def test_aesara_function_simple():
287
+ """ Test aesara_function() with single output. """
288
+ f = aesara_function_([x, y], [x+y])
289
+ assert f(2, 3) == 5
290
+
291
+ def test_aesara_function_multi():
292
+ """ Test aesara_function() with multiple outputs. """
293
+ f = aesara_function_([x, y], [x+y, x-y])
294
+ o1, o2 = f(2, 3)
295
+ assert o1 == 5
296
+ assert o2 == -1
297
+
298
+ def test_aesara_function_numpy():
299
+ """ Test aesara_function() vs Numpy implementation. """
300
+ f = aesara_function_([x, y], [x+y], dim=1,
301
+ dtypes={x: 'float64', y: 'float64'})
302
+ assert np.linalg.norm(f([1, 2], [3, 4]) - np.asarray([4, 6])) < 1e-9
303
+
304
+ f = aesara_function_([x, y], [x+y], dtypes={x: 'float64', y: 'float64'},
305
+ dim=1)
306
+ xx = np.arange(3).astype('float64')
307
+ yy = 2*np.arange(3).astype('float64')
308
+ assert np.linalg.norm(f(xx, yy) - 3*np.arange(3)) < 1e-9
309
+
310
+
311
+ def test_aesara_function_matrix():
312
+ m = sy.Matrix([[x, y], [z, x + y + z]])
313
+ expected = np.array([[1.0, 2.0], [3.0, 1.0 + 2.0 + 3.0]])
314
+ f = aesara_function_([x, y, z], [m])
315
+ np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
316
+ f = aesara_function_([x, y, z], [m], scalar=True)
317
+ np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
318
+ f = aesara_function_([x, y, z], [m, m])
319
+ assert isinstance(f(1.0, 2.0, 3.0), type([]))
320
+ np.testing.assert_allclose(f(1.0, 2.0, 3.0)[0], expected)
321
+ np.testing.assert_allclose(f(1.0, 2.0, 3.0)[1], expected)
322
+
323
+ def test_dim_handling():
324
+ assert dim_handling([x], dim=2) == {x: (False, False)}
325
+ assert dim_handling([x, y], dims={x: 1, y: 2}) == {x: (False, True),
326
+ y: (False, False)}
327
+ assert dim_handling([x], broadcastables={x: (False,)}) == {x: (False,)}
328
+
329
+ def test_aesara_function_kwargs():
330
+ """
331
+ Test passing additional kwargs from aesara_function() to aesara.function().
332
+ """
333
+ import numpy as np
334
+ f = aesara_function_([x, y, z], [x+y], dim=1, on_unused_input='ignore',
335
+ dtypes={x: 'float64', y: 'float64', z: 'float64'})
336
+ assert np.linalg.norm(f([1, 2], [3, 4], [0, 0]) - np.asarray([4, 6])) < 1e-9
337
+
338
+ f = aesara_function_([x, y, z], [x+y],
339
+ dtypes={x: 'float64', y: 'float64', z: 'float64'},
340
+ dim=1, on_unused_input='ignore')
341
+ xx = np.arange(3).astype('float64')
342
+ yy = 2*np.arange(3).astype('float64')
343
+ zz = 2*np.arange(3).astype('float64')
344
+ assert np.linalg.norm(f(xx, yy, zz) - 3*np.arange(3)) < 1e-9
345
+
346
+ def test_aesara_function_scalar():
347
+ """ Test the "scalar" argument to aesara_function(). """
348
+ from aesara.compile.function.types import Function
349
+
350
+ args = [
351
+ ([x, y], [x + y], None, [0]), # Single 0d output
352
+ ([X, Y], [X + Y], None, [2]), # Single 2d output
353
+ ([x, y], [x + y], {x: 0, y: 1}, [1]), # Single 1d output
354
+ ([x, y], [x + y, x - y], None, [0, 0]), # Two 0d outputs
355
+ ([x, y, X, Y], [x + y, X + Y], None, [0, 2]), # One 0d output, one 2d
356
+ ]
357
+
358
+ # Create and test functions with and without the scalar setting
359
+ for inputs, outputs, in_dims, out_dims in args:
360
+ for scalar in [False, True]:
361
+
362
+ f = aesara_function_(inputs, outputs, dims=in_dims, scalar=scalar)
363
+
364
+ # Check the aesara_function attribute is set whether wrapped or not
365
+ assert isinstance(f.aesara_function, Function)
366
+
367
+ # Feed in inputs of the appropriate size and get outputs
368
+ in_values = [
369
+ np.ones([1 if bc else 5 for bc in i.type.broadcastable])
370
+ for i in f.aesara_function.input_storage
371
+ ]
372
+ out_values = f(*in_values)
373
+ if not isinstance(out_values, list):
374
+ out_values = [out_values]
375
+
376
+ # Check output types and shapes
377
+ assert len(out_dims) == len(out_values)
378
+ for d, value in zip(out_dims, out_values):
379
+
380
+ if scalar and d == 0:
381
+ # Should have been converted to a scalar value
382
+ assert isinstance(value, np.number)
383
+
384
+ else:
385
+ # Otherwise should be an array
386
+ assert isinstance(value, np.ndarray)
387
+ assert value.ndim == d
388
+
389
+ def test_aesara_function_bad_kwarg():
390
+ """
391
+ Passing an unknown keyword argument to aesara_function() should raise an
392
+ exception.
393
+ """
394
+ raises(Exception, lambda : aesara_function_([x], [x+1], foobar=3))
395
+
396
+
397
+ def test_slice():
398
+ assert aesara_code_(slice(1, 2, 3)) == slice(1, 2, 3)
399
+
400
+ def theq_slice(s1, s2):
401
+ for attr in ['start', 'stop', 'step']:
402
+ a1 = getattr(s1, attr)
403
+ a2 = getattr(s2, attr)
404
+ if a1 is None or a2 is None:
405
+ if not (a1 is None or a2 is None):
406
+ return False
407
+ elif not theq(a1, a2):
408
+ return False
409
+ return True
410
+
411
+ dtypes = {x: 'int32', y: 'int32'}
412
+ assert theq_slice(aesara_code_(slice(x, y), dtypes=dtypes), slice(xt, yt))
413
+ assert theq_slice(aesara_code_(slice(1, x, 3), dtypes=dtypes), slice(1, xt, 3))
414
+
415
+ def test_MatrixSlice():
416
+ cache = {}
417
+
418
+ n = sy.Symbol('n', integer=True)
419
+ X = sy.MatrixSymbol('X', n, n)
420
+
421
+ Y = X[1:2:3, 4:5:6]
422
+ Yt = aesara_code_(Y, cache=cache)
423
+
424
+ s = Scalar('int64')
425
+ assert tuple(Yt.owner.op.idx_list) == (slice(s, s, s), slice(s, s, s))
426
+ assert Yt.owner.inputs[0] == aesara_code_(X, cache=cache)
427
+ # == doesn't work in Aesara like it does in SymPy. You have to use
428
+ # equals.
429
+ assert all(Yt.owner.inputs[i].data == i for i in range(1, 7))
430
+
431
+ k = sy.Symbol('k')
432
+ aesara_code_(k, dtypes={k: 'int32'})
433
+ start, stop, step = 4, k, 2
434
+ Y = X[start:stop:step]
435
+ Yt = aesara_code_(Y, dtypes={n: 'int32', k: 'int32'})
436
+ # assert Yt.owner.op.idx_list[0].stop == kt
437
+
438
+ def test_BlockMatrix():
439
+ n = sy.Symbol('n', integer=True)
440
+ A, B, C, D = [sy.MatrixSymbol(name, n, n) for name in 'ABCD']
441
+ At, Bt, Ct, Dt = map(aesara_code_, (A, B, C, D))
442
+ Block = sy.BlockMatrix([[A, B], [C, D]])
443
+ Blockt = aesara_code_(Block)
444
+ solutions = [aet.join(0, aet.join(1, At, Bt), aet.join(1, Ct, Dt)),
445
+ aet.join(1, aet.join(0, At, Ct), aet.join(0, Bt, Dt))]
446
+ assert any(theq(Blockt, solution) for solution in solutions)
447
+
448
+ @SKIP
449
+ def test_BlockMatrix_Inverse_execution():
450
+ k, n = 2, 4
451
+ dtype = 'float32'
452
+ A = sy.MatrixSymbol('A', n, k)
453
+ B = sy.MatrixSymbol('B', n, n)
454
+ inputs = A, B
455
+ output = B.I*A
456
+
457
+ cutsizes = {A: [(n//2, n//2), (k//2, k//2)],
458
+ B: [(n//2, n//2), (n//2, n//2)]}
459
+ cutinputs = [sy.blockcut(i, *cutsizes[i]) for i in inputs]
460
+ cutoutput = output.subs(dict(zip(inputs, cutinputs)))
461
+
462
+ dtypes = dict(zip(inputs, [dtype]*len(inputs)))
463
+ f = aesara_function_(inputs, [output], dtypes=dtypes, cache={})
464
+ fblocked = aesara_function_(inputs, [sy.block_collapse(cutoutput)],
465
+ dtypes=dtypes, cache={})
466
+
467
+ ninputs = [np.random.rand(*x.shape).astype(dtype) for x in inputs]
468
+ ninputs = [np.arange(n*k).reshape(A.shape).astype(dtype),
469
+ np.eye(n).astype(dtype)]
470
+ ninputs[1] += np.ones(B.shape)*1e-5
471
+
472
+ assert np.allclose(f(*ninputs), fblocked(*ninputs), rtol=1e-5)
473
+
474
+ def test_DenseMatrix():
475
+ from aesara.tensor.basic import Join
476
+
477
+ t = sy.Symbol('theta')
478
+ for MatrixType in [sy.Matrix, sy.ImmutableMatrix]:
479
+ X = MatrixType([[sy.cos(t), -sy.sin(t)], [sy.sin(t), sy.cos(t)]])
480
+ tX = aesara_code_(X)
481
+ assert isinstance(tX, TensorVariable)
482
+ assert isinstance(tX.owner.op, Join)
483
+
484
+
485
+ def test_cache_basic():
486
+ """ Test single symbol-like objects are cached when printed by themselves. """
487
+
488
+ # Pairs of objects which should be considered equivalent with respect to caching
489
+ pairs = [
490
+ (x, sy.Symbol('x')),
491
+ (X, sy.MatrixSymbol('X', *X.shape)),
492
+ (f_t, sy.Function('f')(sy.Symbol('t'))),
493
+ ]
494
+
495
+ for s1, s2 in pairs:
496
+ cache = {}
497
+ st = aesara_code_(s1, cache=cache)
498
+
499
+ # Test hit with same instance
500
+ assert aesara_code_(s1, cache=cache) is st
501
+
502
+ # Test miss with same instance but new cache
503
+ assert aesara_code_(s1, cache={}) is not st
504
+
505
+ # Test hit with different but equivalent instance
506
+ assert aesara_code_(s2, cache=cache) is st
507
+
508
+ def test_global_cache():
509
+ """ Test use of the global cache. """
510
+ from sympy.printing.aesaracode import global_cache
511
+
512
+ backup = dict(global_cache)
513
+ try:
514
+ # Temporarily empty global cache
515
+ global_cache.clear()
516
+
517
+ for s in [x, X, f_t]:
518
+ st = aesara_code(s)
519
+ assert aesara_code(s) is st
520
+
521
+ finally:
522
+ # Restore global cache
523
+ global_cache.update(backup)
524
+
525
+ def test_cache_types_distinct():
526
+ """
527
+ Test that symbol-like objects of different types (Symbol, MatrixSymbol,
528
+ AppliedUndef) are distinguished by the cache even if they have the same
529
+ name.
530
+ """
531
+ symbols = [sy.Symbol('f_t'), sy.MatrixSymbol('f_t', 4, 4), f_t]
532
+
533
+ cache = {} # Single shared cache
534
+ printed = {}
535
+
536
+ for s in symbols:
537
+ st = aesara_code_(s, cache=cache)
538
+ assert st not in printed.values()
539
+ printed[s] = st
540
+
541
+ # Check all printed objects are distinct
542
+ assert len(set(map(id, printed.values()))) == len(symbols)
543
+
544
+ # Check retrieving
545
+ for s, st in printed.items():
546
+ assert aesara_code(s, cache=cache) is st
547
+
548
+ def test_symbols_are_created_once():
549
+ """
550
+ Test that a symbol is cached and reused when it appears in an expression
551
+ more than once.
552
+ """
553
+ expr = sy.Add(x, x, evaluate=False)
554
+ comp = aesara_code_(expr)
555
+
556
+ assert theq(comp, xt + xt)
557
+ assert not theq(comp, xt + aesara_code_(x))
558
+
559
+ def test_cache_complex():
560
+ """
561
+ Test caching on a complicated expression with multiple symbols appearing
562
+ multiple times.
563
+ """
564
+ expr = x ** 2 + (y - sy.exp(x)) * sy.sin(z - x * y)
565
+ symbol_names = {s.name for s in expr.free_symbols}
566
+ expr_t = aesara_code_(expr)
567
+
568
+ # Iterate through variables in the Aesara computational graph that the
569
+ # printed expression depends on
570
+ seen = set()
571
+ for v in aesara.graph.basic.ancestors([expr_t]):
572
+ # Owner-less, non-constant variables should be our symbols
573
+ if v.owner is None and not isinstance(v, aesara.graph.basic.Constant):
574
+ # Check it corresponds to a symbol and appears only once
575
+ assert v.name in symbol_names
576
+ assert v.name not in seen
577
+ seen.add(v.name)
578
+
579
+ # Check all were present
580
+ assert seen == symbol_names
581
+
582
+
583
+ def test_Piecewise():
584
+ # A piecewise linear
585
+ expr = sy.Piecewise((0, x<0), (x, x<2), (1, True)) # ___/III
586
+ result = aesara_code_(expr)
587
+ assert result.owner.op == aet.switch
588
+
589
+ expected = aet.switch(xt<0, 0, aet.switch(xt<2, xt, 1))
590
+ assert theq(result, expected)
591
+
592
+ expr = sy.Piecewise((x, x < 0))
593
+ result = aesara_code_(expr)
594
+ expected = aet.switch(xt < 0, xt, np.nan)
595
+ assert theq(result, expected)
596
+
597
+ expr = sy.Piecewise((0, sy.And(x>0, x<2)), \
598
+ (x, sy.Or(x>2, x<0)))
599
+ result = aesara_code_(expr)
600
+ expected = aet.switch(aet.and_(xt>0,xt<2), 0, \
601
+ aet.switch(aet.or_(xt>2, xt<0), xt, np.nan))
602
+ assert theq(result, expected)
603
+
604
+
605
+ def test_Relationals():
606
+ assert theq(aesara_code_(sy.Eq(x, y)), aet.eq(xt, yt))
607
+ # assert theq(aesara_code_(sy.Ne(x, y)), aet.neq(xt, yt)) # TODO - implement
608
+ assert theq(aesara_code_(x > y), xt > yt)
609
+ assert theq(aesara_code_(x < y), xt < yt)
610
+ assert theq(aesara_code_(x >= y), xt >= yt)
611
+ assert theq(aesara_code_(x <= y), xt <= yt)
612
+
613
+
614
+ def test_complexfunctions():
615
+ dtypes = {x:'complex128', y:'complex128'}
616
+ xt, yt = aesara_code(x, dtypes=dtypes), aesara_code(y, dtypes=dtypes)
617
+ from sympy.functions.elementary.complexes import conjugate
618
+ from aesara.tensor import as_tensor_variable as atv
619
+ from aesara.tensor import complex as cplx
620
+ assert theq(aesara_code(y*conjugate(x), dtypes=dtypes), yt*(xt.conj()))
621
+ assert theq(aesara_code((1+2j)*x), xt*(atv(1.0)+atv(2.0)*cplx(0,1)))
622
+
623
+
624
+ def test_constantfunctions():
625
+ tf = aesara_function([],[1+1j])
626
+ assert(tf()==1+1j)
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_c.py ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import (
2
+ S, pi, oo, Symbol, symbols, Rational, Integer, Float, Function, Mod, GoldenRatio, EulerGamma, Catalan,
3
+ Lambda, Dummy, nan, Mul, Pow, UnevaluatedExpr
4
+ )
5
+ from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
6
+ from sympy.functions import (
7
+ Abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceiling, cos, cosh, erf,
8
+ erfc, exp, floor, gamma, log, loggamma, Max, Min, Piecewise, sign, sin, sinh,
9
+ sqrt, tan, tanh, fibonacci, lucas
10
+ )
11
+ from sympy.sets import Range
12
+ from sympy.logic import ITE, Implies, Equivalent
13
+ from sympy.codegen import For, aug_assign, Assignment
14
+ from sympy.testing.pytest import raises, XFAIL
15
+ from sympy.printing.c import C89CodePrinter, C99CodePrinter, get_math_macros
16
+ from sympy.codegen.ast import (
17
+ AddAugmentedAssignment, Element, Type, FloatType, Declaration, Pointer, Variable, value_const, pointer_const,
18
+ While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall, Return,
19
+ real, float32, float64, float80, float128, intc, Comment, CodeBlock
20
+ )
21
+ from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, fma, log10, Cbrt, hypot, Sqrt
22
+ from sympy.codegen.cnodes import restrict
23
+ from sympy.utilities.lambdify import implemented_function
24
+ from sympy.tensor import IndexedBase, Idx
25
+ from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix
26
+
27
+ from sympy.printing.codeprinter import ccode
28
+
29
+ x, y, z = symbols('x,y,z')
30
+
31
+
32
+ def test_printmethod():
33
+ class fabs(Abs):
34
+ def _ccode(self, printer):
35
+ return "fabs(%s)" % printer._print(self.args[0])
36
+
37
+ assert ccode(fabs(x)) == "fabs(x)"
38
+
39
+
40
+ def test_ccode_sqrt():
41
+ assert ccode(sqrt(x)) == "sqrt(x)"
42
+ assert ccode(x**0.5) == "sqrt(x)"
43
+ assert ccode(sqrt(x)) == "sqrt(x)"
44
+
45
+
46
+ def test_ccode_Pow():
47
+ assert ccode(x**3) == "pow(x, 3)"
48
+ assert ccode(x**(y**3)) == "pow(x, pow(y, 3))"
49
+ g = implemented_function('g', Lambda(x, 2*x))
50
+ assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
51
+ "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)"
52
+ assert ccode(x**-1.0) == '1.0/x'
53
+ assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0/3.0)'
54
+ assert ccode(x**Rational(2, 3), type_aliases={real: float80}) == 'powl(x, 2.0L/3.0L)'
55
+ _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"),
56
+ (lambda base, exp: not exp.is_integer, "pow")]
57
+ assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)'
58
+ assert ccode(x**0.5, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 0.5)'
59
+ assert ccode(x**Rational(16, 5), user_functions={'Pow': _cond_cfunc}) == 'pow(x, 16.0/5.0)'
60
+ _cond_cfunc2 = [(lambda base, exp: base == 2, lambda base, exp: 'exp2(%s)' % exp),
61
+ (lambda base, exp: base != 2, 'pow')]
62
+ # Related to gh-11353
63
+ assert ccode(2**x, user_functions={'Pow': _cond_cfunc2}) == 'exp2(x)'
64
+ assert ccode(x**2, user_functions={'Pow': _cond_cfunc2}) == 'pow(x, 2)'
65
+ # For issue 14160
66
+ assert ccode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
67
+ evaluate=False)) == '-2*x/(y*y)'
68
+
69
+
70
+ def test_ccode_Max():
71
+ # Test for gh-11926
72
+ assert ccode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))'
73
+
74
+
75
+ def test_ccode_Min_performance():
76
+ #Shouldn't take more than a few seconds
77
+ big_min = Min(*symbols('a[0:50]'))
78
+ for curr_standard in ('c89', 'c99', 'c11'):
79
+ output = ccode(big_min, standard=curr_standard)
80
+ assert output.count('(') == output.count(')')
81
+
82
+
83
+ def test_ccode_constants_mathh():
84
+ assert ccode(exp(1)) == "M_E"
85
+ assert ccode(pi) == "M_PI"
86
+ assert ccode(oo, standard='c89') == "HUGE_VAL"
87
+ assert ccode(-oo, standard='c89') == "-HUGE_VAL"
88
+ assert ccode(oo) == "INFINITY"
89
+ assert ccode(-oo, standard='c99') == "-INFINITY"
90
+ assert ccode(pi, type_aliases={real: float80}) == "M_PIl"
91
+
92
+
93
+ def test_ccode_constants_other():
94
+ assert ccode(2*GoldenRatio) == "const double GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17)
95
+ assert ccode(
96
+ 2*Catalan) == "const double Catalan = %s;\n2*Catalan" % Catalan.evalf(17)
97
+ assert ccode(2*EulerGamma) == "const double EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17)
98
+
99
+
100
+ def test_ccode_Rational():
101
+ assert ccode(Rational(3, 7)) == "3.0/7.0"
102
+ assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L"
103
+ assert ccode(Rational(18, 9)) == "2"
104
+ assert ccode(Rational(3, -7)) == "-3.0/7.0"
105
+ assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L"
106
+ assert ccode(Rational(-3, -7)) == "3.0/7.0"
107
+ assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L"
108
+ assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0"
109
+ assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L"
110
+ assert ccode(Rational(3, 7)*x) == "(3.0/7.0)*x"
111
+ assert ccode(Rational(3, 7)*x, type_aliases={real: float80}) == "(3.0L/7.0L)*x"
112
+
113
+
114
+ def test_ccode_Integer():
115
+ assert ccode(Integer(67)) == "67"
116
+ assert ccode(Integer(-1)) == "-1"
117
+
118
+
119
+ def test_ccode_functions():
120
+ assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))"
121
+
122
+
123
+ def test_ccode_inline_function():
124
+ x = symbols('x')
125
+ g = implemented_function('g', Lambda(x, 2*x))
126
+ assert ccode(g(x)) == "2*x"
127
+ g = implemented_function('g', Lambda(x, 2*x/Catalan))
128
+ assert ccode(
129
+ g(x)) == "const double Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17)
130
+ A = IndexedBase('A')
131
+ i = Idx('i', symbols('n', integer=True))
132
+ g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
133
+ assert ccode(g(A[i]), assign_to=A[i]) == (
134
+ "for (int i=0; i<n; i++){\n"
135
+ " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
136
+ "}"
137
+ )
138
+
139
+
140
+ def test_ccode_exceptions():
141
+ assert ccode(gamma(x), standard='C99') == "tgamma(x)"
142
+ gamma_c89 = ccode(gamma(x), standard='C89')
143
+ assert 'not supported in c' in gamma_c89.lower()
144
+ gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=False)
145
+ assert 'not supported in c' in gamma_c89.lower()
146
+ gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=True)
147
+ assert 'not supported in c' not in gamma_c89.lower()
148
+
149
+
150
+ def test_ccode_functions2():
151
+ assert ccode(ceiling(x)) == "ceil(x)"
152
+ assert ccode(Abs(x)) == "fabs(x)"
153
+ assert ccode(gamma(x)) == "tgamma(x)"
154
+ r, s = symbols('r,s', real=True)
155
+ assert ccode(Mod(ceiling(r), ceiling(s))) == '((ceil(r) % ceil(s)) + '\
156
+ 'ceil(s)) % ceil(s)'
157
+ assert ccode(Mod(r, s)) == "fmod(r, s)"
158
+ p1, p2 = symbols('p1 p2', integer=True, positive=True)
159
+ assert ccode(Mod(p1, p2)) == 'p1 % p2'
160
+ assert ccode(Mod(p1, p2 + 3)) == 'p1 % (p2 + 3)'
161
+ assert ccode(Mod(-3, -7, evaluate=False)) == '(-3) % (-7)'
162
+ assert ccode(-Mod(3, 7, evaluate=False)) == '-(3 % 7)'
163
+ assert ccode(r*Mod(p1, p2)) == 'r*(p1 % p2)'
164
+ assert ccode(Mod(p1, p2)**s) == 'pow(p1 % p2, s)'
165
+ n = symbols('n', integer=True, negative=True)
166
+ assert ccode(Mod(-n, p2)) == '(-n) % p2'
167
+ assert ccode(fibonacci(n)) == '(1.0/5.0)*pow(2, -n)*sqrt(5)*(-pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))'
168
+ assert ccode(lucas(n)) == 'pow(2, -n)*(pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))'
169
+
170
+
171
+ def test_ccode_user_functions():
172
+ x = symbols('x', integer=False)
173
+ n = symbols('n', integer=True)
174
+ custom_functions = {
175
+ "ceiling": "ceil",
176
+ "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
177
+ }
178
+ assert ccode(ceiling(x), user_functions=custom_functions) == "ceil(x)"
179
+ assert ccode(Abs(x), user_functions=custom_functions) == "fabs(x)"
180
+ assert ccode(Abs(n), user_functions=custom_functions) == "abs(n)"
181
+
182
+ expr = Symbol('a')
183
+ muladd = Function('muladd')
184
+ for i in range(0, 100):
185
+ # the large number of terms acts as a regression test for gh-23839
186
+ expr = muladd(Rational(1, 2), Symbol(f'a{i}'), expr)
187
+ out = ccode(expr, user_functions={'muladd':'muladd'})
188
+ assert 'a99' in out
189
+ assert out.count('muladd') == 100
190
+
191
+
192
+ def test_ccode_boolean():
193
+ assert ccode(True) == "true"
194
+ assert ccode(S.true) == "true"
195
+ assert ccode(False) == "false"
196
+ assert ccode(S.false) == "false"
197
+ assert ccode(x & y) == "x && y"
198
+ assert ccode(x | y) == "x || y"
199
+ assert ccode(~x) == "!x"
200
+ assert ccode(x & y & z) == "x && y && z"
201
+ assert ccode(x | y | z) == "x || y || z"
202
+ assert ccode((x & y) | z) == "z || x && y"
203
+ assert ccode((x | y) & z) == "z && (x || y)"
204
+ # Automatic rewrites
205
+ assert ccode(x ^ y) == '(x || y) && (!x || !y)'
206
+ assert ccode((x ^ y) ^ z) == '(x || y || z) && (x || !y || !z) && (y || !x || !z) && (z || !x || !y)'
207
+ assert ccode(Implies(x, y)) == 'y || !x'
208
+ assert ccode(Equivalent(x, z ^ y, Implies(z, x))) == '(x || (y || !z) && (z || !y)) && (z && !x || (y || z) && (!y || !z))'
209
+
210
+
211
+ def test_ccode_Relational():
212
+ assert ccode(Eq(x, y)) == "x == y"
213
+ assert ccode(Ne(x, y)) == "x != y"
214
+ assert ccode(Le(x, y)) == "x <= y"
215
+ assert ccode(Lt(x, y)) == "x < y"
216
+ assert ccode(Gt(x, y)) == "x > y"
217
+ assert ccode(Ge(x, y)) == "x >= y"
218
+
219
+
220
+ def test_ccode_Piecewise():
221
+ expr = Piecewise((x, x < 1), (x**2, True))
222
+ assert ccode(expr) == (
223
+ "((x < 1) ? (\n"
224
+ " x\n"
225
+ ")\n"
226
+ ": (\n"
227
+ " pow(x, 2)\n"
228
+ "))")
229
+ assert ccode(expr, assign_to="c") == (
230
+ "if (x < 1) {\n"
231
+ " c = x;\n"
232
+ "}\n"
233
+ "else {\n"
234
+ " c = pow(x, 2);\n"
235
+ "}")
236
+ expr = Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))
237
+ assert ccode(expr) == (
238
+ "((x < 1) ? (\n"
239
+ " x\n"
240
+ ")\n"
241
+ ": ((x < 2) ? (\n"
242
+ " x + 1\n"
243
+ ")\n"
244
+ ": (\n"
245
+ " pow(x, 2)\n"
246
+ ")))")
247
+ assert ccode(expr, assign_to='c') == (
248
+ "if (x < 1) {\n"
249
+ " c = x;\n"
250
+ "}\n"
251
+ "else if (x < 2) {\n"
252
+ " c = x + 1;\n"
253
+ "}\n"
254
+ "else {\n"
255
+ " c = pow(x, 2);\n"
256
+ "}")
257
+ # Check that Piecewise without a True (default) condition error
258
+ expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
259
+ raises(ValueError, lambda: ccode(expr))
260
+
261
+
262
+ def test_ccode_sinc():
263
+ from sympy.functions.elementary.trigonometric import sinc
264
+ expr = sinc(x)
265
+ assert ccode(expr) == (
266
+ "((x != 0) ? (\n"
267
+ " sin(x)/x\n"
268
+ ")\n"
269
+ ": (\n"
270
+ " 1\n"
271
+ "))")
272
+
273
+
274
+ def test_ccode_Piecewise_deep():
275
+ p = ccode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)))
276
+ assert p == (
277
+ "2*((x < 1) ? (\n"
278
+ " x\n"
279
+ ")\n"
280
+ ": ((x < 2) ? (\n"
281
+ " x + 1\n"
282
+ ")\n"
283
+ ": (\n"
284
+ " pow(x, 2)\n"
285
+ ")))")
286
+ expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1
287
+ assert ccode(expr) == (
288
+ "pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n"
289
+ " 0\n"
290
+ ")\n"
291
+ ": (\n"
292
+ " 1\n"
293
+ ")) + cos(z) - 1")
294
+ assert ccode(expr, assign_to='c') == (
295
+ "c = pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n"
296
+ " 0\n"
297
+ ")\n"
298
+ ": (\n"
299
+ " 1\n"
300
+ ")) + cos(z) - 1;")
301
+
302
+
303
+ def test_ccode_ITE():
304
+ expr = ITE(x < 1, y, z)
305
+ assert ccode(expr) == (
306
+ "((x < 1) ? (\n"
307
+ " y\n"
308
+ ")\n"
309
+ ": (\n"
310
+ " z\n"
311
+ "))")
312
+
313
+
314
+ def test_ccode_settings():
315
+ raises(TypeError, lambda: ccode(sin(x), method="garbage"))
316
+
317
+
318
+ def test_ccode_Indexed():
319
+ s, n, m, o = symbols('s n m o', integer=True)
320
+ i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
321
+
322
+ x = IndexedBase('x')[j]
323
+ A = IndexedBase('A')[i, j]
324
+ B = IndexedBase('B')[i, j, k]
325
+
326
+ p = C99CodePrinter()
327
+
328
+ assert p._print_Indexed(x) == 'x[j]'
329
+ assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
330
+ assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
331
+
332
+ A = IndexedBase('A', shape=(5,3))[i, j]
333
+ assert p._print_Indexed(A) == 'A[%s]' % (3*i + j)
334
+
335
+ A = IndexedBase('A', shape=(5,3), strides='F')[i, j]
336
+ assert ccode(A) == 'A[%s]' % (i + 5*j)
337
+
338
+ A = IndexedBase('A', shape=(29,29), strides=(1, s), offset=o)[i, j]
339
+ assert ccode(A) == 'A[o + s*j + i]'
340
+
341
+ Abase = IndexedBase('A', strides=(s, m, n), offset=o)
342
+ assert ccode(Abase[i, j, k]) == 'A[m*j + n*k + o + s*i]'
343
+ assert ccode(Abase[2, 3, k]) == 'A[3*m + n*k + o + 2*s]'
344
+
345
+
346
+ def test_Element():
347
+ assert ccode(Element('x', 'ij')) == 'x[i][j]'
348
+ assert ccode(Element('x', 'ij', strides='kl', offset='o')) == 'x[i*k + j*l + o]'
349
+ assert ccode(Element('x', (3,))) == 'x[3]'
350
+ assert ccode(Element('x', (3,4,5))) == 'x[3][4][5]'
351
+
352
+
353
+ def test_ccode_Indexed_without_looking_for_contraction():
354
+ len_y = 5
355
+ y = IndexedBase('y', shape=(len_y,))
356
+ x = IndexedBase('x', shape=(len_y,))
357
+ Dy = IndexedBase('Dy', shape=(len_y-1,))
358
+ i = Idx('i', len_y-1)
359
+ e = Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
360
+ code0 = ccode(e.rhs, assign_to=e.lhs, contract=False)
361
+ assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1)
362
+
363
+
364
+ def test_ccode_loops_matrix_vector():
365
+ n, m = symbols('n m', integer=True)
366
+ A = IndexedBase('A')
367
+ x = IndexedBase('x')
368
+ y = IndexedBase('y')
369
+ i = Idx('i', m)
370
+ j = Idx('j', n)
371
+
372
+ s = (
373
+ 'for (int i=0; i<m; i++){\n'
374
+ ' y[i] = 0;\n'
375
+ '}\n'
376
+ 'for (int i=0; i<m; i++){\n'
377
+ ' for (int j=0; j<n; j++){\n'
378
+ ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\
379
+ ' }\n'
380
+ '}'
381
+ )
382
+ assert ccode(A[i, j]*x[j], assign_to=y[i]) == s
383
+
384
+
385
+ def test_dummy_loops():
386
+ i, m = symbols('i m', integer=True, cls=Dummy)
387
+ x = IndexedBase('x')
388
+ y = IndexedBase('y')
389
+ i = Idx(i, m)
390
+
391
+ expected = (
392
+ 'for (int i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n'
393
+ ' y[i_%(icount)i] = x[i_%(icount)i];\n'
394
+ '}'
395
+ ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
396
+
397
+ assert ccode(x[i], assign_to=y[i]) == expected
398
+
399
+
400
+ def test_ccode_loops_add():
401
+ n, m = symbols('n m', integer=True)
402
+ A = IndexedBase('A')
403
+ x = IndexedBase('x')
404
+ y = IndexedBase('y')
405
+ z = IndexedBase('z')
406
+ i = Idx('i', m)
407
+ j = Idx('j', n)
408
+
409
+ s = (
410
+ 'for (int i=0; i<m; i++){\n'
411
+ ' y[i] = x[i] + z[i];\n'
412
+ '}\n'
413
+ 'for (int i=0; i<m; i++){\n'
414
+ ' for (int j=0; j<n; j++){\n'
415
+ ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\
416
+ ' }\n'
417
+ '}'
418
+ )
419
+ assert ccode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == s
420
+
421
+
422
+ def test_ccode_loops_multiple_contractions():
423
+ n, m, o, p = symbols('n m o p', integer=True)
424
+ a = IndexedBase('a')
425
+ b = IndexedBase('b')
426
+ y = IndexedBase('y')
427
+ i = Idx('i', m)
428
+ j = Idx('j', n)
429
+ k = Idx('k', o)
430
+ l = Idx('l', p)
431
+
432
+ s = (
433
+ 'for (int i=0; i<m; i++){\n'
434
+ ' y[i] = 0;\n'
435
+ '}\n'
436
+ 'for (int i=0; i<m; i++){\n'
437
+ ' for (int j=0; j<n; j++){\n'
438
+ ' for (int k=0; k<o; k++){\n'
439
+ ' for (int l=0; l<p; l++){\n'
440
+ ' y[i] = a[%s]*b[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
441
+ ' }\n'
442
+ ' }\n'
443
+ ' }\n'
444
+ '}'
445
+ )
446
+ assert ccode(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == s
447
+
448
+
449
+ def test_ccode_loops_addfactor():
450
+ n, m, o, p = symbols('n m o p', integer=True)
451
+ a = IndexedBase('a')
452
+ b = IndexedBase('b')
453
+ c = IndexedBase('c')
454
+ y = IndexedBase('y')
455
+ i = Idx('i', m)
456
+ j = Idx('j', n)
457
+ k = Idx('k', o)
458
+ l = Idx('l', p)
459
+
460
+ s = (
461
+ 'for (int i=0; i<m; i++){\n'
462
+ ' y[i] = 0;\n'
463
+ '}\n'
464
+ 'for (int i=0; i<m; i++){\n'
465
+ ' for (int j=0; j<n; j++){\n'
466
+ ' for (int k=0; k<o; k++){\n'
467
+ ' for (int l=0; l<p; l++){\n'
468
+ ' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
469
+ ' }\n'
470
+ ' }\n'
471
+ ' }\n'
472
+ '}'
473
+ )
474
+ assert ccode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) == s
475
+
476
+
477
+ def test_ccode_loops_multiple_terms():
478
+ n, m, o, p = symbols('n m o p', integer=True)
479
+ a = IndexedBase('a')
480
+ b = IndexedBase('b')
481
+ c = IndexedBase('c')
482
+ y = IndexedBase('y')
483
+ i = Idx('i', m)
484
+ j = Idx('j', n)
485
+ k = Idx('k', o)
486
+
487
+ s0 = (
488
+ 'for (int i=0; i<m; i++){\n'
489
+ ' y[i] = 0;\n'
490
+ '}\n'
491
+ )
492
+ s1 = (
493
+ 'for (int i=0; i<m; i++){\n'
494
+ ' for (int j=0; j<n; j++){\n'
495
+ ' for (int k=0; k<o; k++){\n'
496
+ ' y[i] = b[j]*b[k]*c[%s] + y[i];\n' % (i*n*o + j*o + k) +\
497
+ ' }\n'
498
+ ' }\n'
499
+ '}\n'
500
+ )
501
+ s2 = (
502
+ 'for (int i=0; i<m; i++){\n'
503
+ ' for (int k=0; k<o; k++){\n'
504
+ ' y[i] = a[%s]*b[k] + y[i];\n' % (i*o + k) +\
505
+ ' }\n'
506
+ '}\n'
507
+ )
508
+ s3 = (
509
+ 'for (int i=0; i<m; i++){\n'
510
+ ' for (int j=0; j<n; j++){\n'
511
+ ' y[i] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\
512
+ ' }\n'
513
+ '}\n'
514
+ )
515
+ c = ccode(b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i])
516
+ assert (c == s0 + s1 + s2 + s3[:-1] or
517
+ c == s0 + s1 + s3 + s2[:-1] or
518
+ c == s0 + s2 + s1 + s3[:-1] or
519
+ c == s0 + s2 + s3 + s1[:-1] or
520
+ c == s0 + s3 + s1 + s2[:-1] or
521
+ c == s0 + s3 + s2 + s1[:-1])
522
+
523
+
524
+ def test_dereference_printing():
525
+ expr = x + y + sin(z) + z
526
+ assert ccode(expr, dereference=[z]) == "x + y + (*z) + sin((*z))"
527
+
528
+
529
+ def test_Matrix_printing():
530
+ # Test returning a Matrix
531
+ mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
532
+ A = MatrixSymbol('A', 3, 1)
533
+ assert ccode(mat, A) == (
534
+ "A[0] = x*y;\n"
535
+ "if (y > 0) {\n"
536
+ " A[1] = x + 2;\n"
537
+ "}\n"
538
+ "else {\n"
539
+ " A[1] = y;\n"
540
+ "}\n"
541
+ "A[2] = sin(z);")
542
+ # Test using MatrixElements in expressions
543
+ expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
544
+ assert ccode(expr) == (
545
+ "((x > 0) ? (\n"
546
+ " 2*A[2]\n"
547
+ ")\n"
548
+ ": (\n"
549
+ " A[2]\n"
550
+ ")) + sin(A[1]) + A[0]")
551
+ # Test using MatrixElements in a Matrix
552
+ q = MatrixSymbol('q', 5, 1)
553
+ M = MatrixSymbol('M', 3, 3)
554
+ m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
555
+ [q[1,0] + q[2,0], q[3, 0], 5],
556
+ [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
557
+ assert ccode(m, M) == (
558
+ "M[0] = sin(q[1]);\n"
559
+ "M[1] = 0;\n"
560
+ "M[2] = cos(q[2]);\n"
561
+ "M[3] = q[1] + q[2];\n"
562
+ "M[4] = q[3];\n"
563
+ "M[5] = 5;\n"
564
+ "M[6] = 2*q[4]/q[1];\n"
565
+ "M[7] = sqrt(q[0]) + 4;\n"
566
+ "M[8] = 0;")
567
+
568
+
569
+ def test_sparse_matrix():
570
+ # gh-15791
571
+ assert 'Not supported in C' in ccode(SparseMatrix([[1, 2, 3]]))
572
+
573
+
574
+ def test_ccode_reserved_words():
575
+ x, y = symbols('x, if')
576
+ with raises(ValueError):
577
+ ccode(y**2, error_on_reserved=True, standard='C99')
578
+ assert ccode(y**2) == 'pow(if_, 2)'
579
+ assert ccode(x * y**2, dereference=[y]) == 'pow((*if_), 2)*x'
580
+ assert ccode(y**2, reserved_word_suffix='_unreserved') == 'pow(if_unreserved, 2)'
581
+
582
+
583
+ def test_ccode_sign():
584
+ expr1, ref1 = sign(x) * y, 'y*(((x) > 0) - ((x) < 0))'
585
+ expr2, ref2 = sign(cos(x)), '(((cos(x)) > 0) - ((cos(x)) < 0))'
586
+ expr3, ref3 = sign(2 * x + x**2) * x + x**2, 'pow(x, 2) + x*(((pow(x, 2) + 2*x) > 0) - ((pow(x, 2) + 2*x) < 0))'
587
+ assert ccode(expr1) == ref1
588
+ assert ccode(expr1, 'z') == 'z = %s;' % ref1
589
+ assert ccode(expr2) == ref2
590
+ assert ccode(expr3) == ref3
591
+
592
+ def test_ccode_Assignment():
593
+ assert ccode(Assignment(x, y + z)) == 'x = y + z;'
594
+ assert ccode(aug_assign(x, '+', y + z)) == 'x += y + z;'
595
+
596
+
597
+ def test_ccode_For():
598
+ f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)])
599
+ assert ccode(f) == ("for (x = 0; x < 10; x += 2) {\n"
600
+ " y *= x;\n"
601
+ "}")
602
+
603
+ def test_ccode_Max_Min():
604
+ assert ccode(Max(x, 0), standard='C89') == '((0 > x) ? 0 : x)'
605
+ assert ccode(Max(x, 0), standard='C99') == 'fmax(0, x)'
606
+ assert ccode(Min(x, 0, sqrt(x)), standard='c89') == (
607
+ '((0 < ((x < sqrt(x)) ? x : sqrt(x))) ? 0 : ((x < sqrt(x)) ? x : sqrt(x)))'
608
+ )
609
+
610
+ def test_ccode_standard():
611
+ assert ccode(expm1(x), standard='c99') == 'expm1(x)'
612
+ assert ccode(nan, standard='c99') == 'NAN'
613
+ assert ccode(float('nan'), standard='c99') == 'NAN'
614
+
615
+
616
+ def test_C89CodePrinter():
617
+ c89printer = C89CodePrinter()
618
+ assert c89printer.language == 'C'
619
+ assert c89printer.standard == 'C89'
620
+ assert 'void' in c89printer.reserved_words
621
+ assert 'template' not in c89printer.reserved_words
622
+
623
+
624
+ def test_C99CodePrinter():
625
+ assert C99CodePrinter().doprint(expm1(x)) == 'expm1(x)'
626
+ assert C99CodePrinter().doprint(log1p(x)) == 'log1p(x)'
627
+ assert C99CodePrinter().doprint(exp2(x)) == 'exp2(x)'
628
+ assert C99CodePrinter().doprint(log2(x)) == 'log2(x)'
629
+ assert C99CodePrinter().doprint(fma(x, y, -z)) == 'fma(x, y, -z)'
630
+ assert C99CodePrinter().doprint(log10(x)) == 'log10(x)'
631
+ assert C99CodePrinter().doprint(Cbrt(x)) == 'cbrt(x)' # note Cbrt due to cbrt already taken.
632
+ assert C99CodePrinter().doprint(hypot(x, y)) == 'hypot(x, y)'
633
+ assert C99CodePrinter().doprint(loggamma(x)) == 'lgamma(x)'
634
+ assert C99CodePrinter().doprint(Max(x, 3, x**2)) == 'fmax(3, fmax(x, pow(x, 2)))'
635
+ assert C99CodePrinter().doprint(Min(x, 3)) == 'fmin(3, x)'
636
+ c99printer = C99CodePrinter()
637
+ assert c99printer.language == 'C'
638
+ assert c99printer.standard == 'C99'
639
+ assert 'restrict' in c99printer.reserved_words
640
+ assert 'using' not in c99printer.reserved_words
641
+
642
+
643
+ @XFAIL
644
+ def test_C99CodePrinter__precision_f80():
645
+ f80_printer = C99CodePrinter({"type_aliases": {real: float80}})
646
+ assert f80_printer.doprint(sin(x+Float('2.1'))) == 'sinl(x + 2.1L)'
647
+
648
+
649
+ def test_C99CodePrinter__precision():
650
+ n = symbols('n', integer=True)
651
+ p = symbols('p', integer=True, positive=True)
652
+ f32_printer = C99CodePrinter({"type_aliases": {real: float32}})
653
+ f64_printer = C99CodePrinter({"type_aliases": {real: float64}})
654
+ f80_printer = C99CodePrinter({"type_aliases": {real: float80}})
655
+ assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)'
656
+ assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)'
657
+ assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)'
658
+
659
+ for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']):
660
+ def check(expr, ref):
661
+ assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper())
662
+ check(Abs(n), 'abs(n)')
663
+ check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})')
664
+ check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))')
665
+ check(exp(x*8.0), 'exp{s}(8.0{S}*x)')
666
+ check(exp2(x), 'exp2{s}(x)')
667
+ check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)')
668
+ check(Mod(p, 2), 'p % 2')
669
+ check(Mod(2*p + 3, 3*p + 5, evaluate=False), '(2*p + 3) % (3*p + 5)')
670
+ check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})')
671
+ check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})')
672
+ check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)')
673
+ check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)')
674
+ check(log2(x*8.0), 'log2{s}(8.0{S}*x)')
675
+ check(log1p(x), 'log1p{s}(x)')
676
+ check(2**x, 'pow{s}(2, x)')
677
+ check(2.0**x, 'pow{s}(2.0{S}, x)')
678
+ check(x**3, 'pow{s}(x, 3)')
679
+ check(x**4.0, 'pow{s}(x, 4.0{S})')
680
+ check(sqrt(3+x), 'sqrt{s}(x + 3)')
681
+ check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})')
682
+ check(hypot(x, y), 'hypot{s}(x, y)')
683
+ check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})')
684
+ check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})')
685
+ check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})')
686
+ check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})')
687
+ check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})')
688
+ check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})')
689
+ check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)')
690
+
691
+ check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})')
692
+ check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})')
693
+ check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})')
694
+ check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})')
695
+ check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})')
696
+ check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})')
697
+ check(erf(42.*x), 'erf{s}(42.0{S}*x)')
698
+ check(erfc(42.*x), 'erfc{s}(42.0{S}*x)')
699
+ check(gamma(x), 'tgamma{s}(x)')
700
+ check(loggamma(x), 'lgamma{s}(x)')
701
+
702
+ check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})")
703
+ check(floor(x + 2.), "floor{s}(x + 2.0{S})")
704
+ check(fma(x, y, -z), 'fma{s}(x, y, -z)')
705
+ check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))')
706
+ check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)')
707
+
708
+
709
+ def test_get_math_macros():
710
+ macros = get_math_macros()
711
+ assert macros[exp(1)] == 'M_E'
712
+ assert macros[1/Sqrt(2)] == 'M_SQRT1_2'
713
+
714
+
715
+ def test_ccode_Declaration():
716
+ i = symbols('i', integer=True)
717
+ var1 = Variable(i, type=Type.from_expr(i))
718
+ dcl1 = Declaration(var1)
719
+ assert ccode(dcl1) == 'int i'
720
+
721
+ var2 = Variable(x, type=float32, attrs={value_const})
722
+ dcl2a = Declaration(var2)
723
+ assert ccode(dcl2a) == 'const float x'
724
+ dcl2b = var2.as_Declaration(value=pi)
725
+ assert ccode(dcl2b) == 'const float x = M_PI'
726
+
727
+ var3 = Variable(y, type=Type('bool'))
728
+ dcl3 = Declaration(var3)
729
+ printer = C89CodePrinter()
730
+ assert 'stdbool.h' not in printer.headers
731
+ assert printer.doprint(dcl3) == 'bool y'
732
+ assert 'stdbool.h' in printer.headers
733
+
734
+ u = symbols('u', real=True)
735
+ ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict})
736
+ dcl4 = Declaration(ptr4)
737
+ assert ccode(dcl4) == 'double * const restrict u'
738
+
739
+ var5 = Variable(x, Type('__float128'), attrs={value_const})
740
+ dcl5a = Declaration(var5)
741
+ assert ccode(dcl5a) == 'const __float128 x'
742
+ var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs)
743
+ dcl5b = Declaration(var5b)
744
+ assert ccode(dcl5b) == 'const __float128 x = M_PI'
745
+
746
+
747
+ def test_C99CodePrinter_custom_type():
748
+ # We will look at __float128 (new in glibc 2.26)
749
+ f128 = FloatType('_Float128', float128.nbits, float128.nmant, float128.nexp)
750
+ p128 = C99CodePrinter({
751
+ "type_aliases": {real: f128},
752
+ "type_literal_suffixes": {f128: 'Q'},
753
+ "type_func_suffixes": {f128: 'f128'},
754
+ "type_math_macro_suffixes": {
755
+ real: 'f128',
756
+ f128: 'f128'
757
+ },
758
+ "type_macros": {
759
+ f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__',)
760
+ }
761
+ })
762
+ assert p128.doprint(x) == 'x'
763
+ assert not p128.headers
764
+ assert not p128.libraries
765
+ assert not p128.macros
766
+ assert p128.doprint(2.0) == '2.0Q'
767
+ assert not p128.headers
768
+ assert not p128.libraries
769
+ assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'}
770
+
771
+ assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q'
772
+ assert p128.doprint(sin(x)) == 'sinf128(x)'
773
+ assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)'
774
+ assert p128.doprint(x**-1.0) == '1.0Q/x'
775
+
776
+ var5 = Variable(x, f128, attrs={value_const})
777
+
778
+ dcl5a = Declaration(var5)
779
+ assert ccode(dcl5a) == 'const _Float128 x'
780
+ var5b = Variable(x, f128, pi, attrs={value_const})
781
+ dcl5b = Declaration(var5b)
782
+ assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128'
783
+ var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const})
784
+ dcl5c = Declaration(var5b)
785
+ assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(f128.decimal_dig)
786
+
787
+
788
+ def test_MatrixElement_printing():
789
+ # test cases for issue #11821
790
+ A = MatrixSymbol("A", 1, 3)
791
+ B = MatrixSymbol("B", 1, 3)
792
+ C = MatrixSymbol("C", 1, 3)
793
+
794
+ assert(ccode(A[0, 0]) == "A[0]")
795
+ assert(ccode(3 * A[0, 0]) == "3*A[0]")
796
+
797
+ F = C[0, 0].subs(C, A - B)
798
+ assert(ccode(F) == "(A - B)[0]")
799
+
800
+ def test_ccode_math_macros():
801
+ assert ccode(z + exp(1)) == 'z + M_E'
802
+ assert ccode(z + log2(exp(1))) == 'z + M_LOG2E'
803
+ assert ccode(z + 1/log(2)) == 'z + M_LOG2E'
804
+ assert ccode(z + log(2)) == 'z + M_LN2'
805
+ assert ccode(z + log(10)) == 'z + M_LN10'
806
+ assert ccode(z + pi) == 'z + M_PI'
807
+ assert ccode(z + pi/2) == 'z + M_PI_2'
808
+ assert ccode(z + pi/4) == 'z + M_PI_4'
809
+ assert ccode(z + 1/pi) == 'z + M_1_PI'
810
+ assert ccode(z + 2/pi) == 'z + M_2_PI'
811
+ assert ccode(z + 2/sqrt(pi)) == 'z + M_2_SQRTPI'
812
+ assert ccode(z + 2/Sqrt(pi)) == 'z + M_2_SQRTPI'
813
+ assert ccode(z + sqrt(2)) == 'z + M_SQRT2'
814
+ assert ccode(z + Sqrt(2)) == 'z + M_SQRT2'
815
+ assert ccode(z + 1/sqrt(2)) == 'z + M_SQRT1_2'
816
+ assert ccode(z + 1/Sqrt(2)) == 'z + M_SQRT1_2'
817
+
818
+
819
+ def test_ccode_Type():
820
+ assert ccode(Type('float')) == 'float'
821
+ assert ccode(intc) == 'int'
822
+
823
+
824
+ def test_ccode_codegen_ast():
825
+ # Note that C only allows comments of the form /* ... */, double forward
826
+ # slash is not standard C, and some C compilers will grind to a halt upon
827
+ # encountering them.
828
+ assert ccode(Comment("this is a comment")) == "/* this is a comment */" # not //
829
+ assert ccode(While(abs(x) > 1, [aug_assign(x, '-', 1)])) == (
830
+ 'while (fabs(x) > 1) {\n'
831
+ ' x -= 1;\n'
832
+ '}'
833
+ )
834
+ assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == (
835
+ '{\n'
836
+ ' x += 1;\n'
837
+ '}'
838
+ )
839
+ inp_x = Declaration(Variable(x, type=real))
840
+ assert ccode(FunctionPrototype(real, 'pwer', [inp_x])) == 'double pwer(double x)'
841
+ assert ccode(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) == (
842
+ 'double pwer(double x){\n'
843
+ ' x = pow(x, 2);\n'
844
+ '}'
845
+ )
846
+
847
+ # Elements of CodeBlock are formatted as statements:
848
+ block = CodeBlock(
849
+ x,
850
+ Print([x, y], "%d %d"),
851
+ FunctionCall('pwer', [x]),
852
+ Return(x),
853
+ )
854
+ assert ccode(block) == '\n'.join([
855
+ 'x;',
856
+ 'printf("%d %d", x, y);',
857
+ 'pwer(x);',
858
+ 'return x;',
859
+ ])
860
+
861
+ def test_ccode_UnevaluatedExpr():
862
+ assert ccode(UnevaluatedExpr(y * x) + z) == "z + x*y"
863
+ assert ccode(UnevaluatedExpr(y + x) + z) == "z + (x + y)" # gh-21955
864
+ w = symbols('w')
865
+ assert ccode(UnevaluatedExpr(y + x) + UnevaluatedExpr(z + w)) == "(w + z) + (x + y)"
866
+
867
+ p, q, r = symbols("p q r", real=True)
868
+ q_r = UnevaluatedExpr(q + r)
869
+ expr = abs(exp(p+q_r))
870
+ assert ccode(expr) == "exp(p + (q + r))"
871
+
872
+
873
+ def test_ccode_array_like_containers():
874
+ assert ccode([2,3,4]) == "{2, 3, 4}"
875
+ assert ccode((2,3,4)) == "{2, 3, 4}"
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_codeprinter.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.printing.codeprinter import CodePrinter
2
+ from sympy.core import symbols
3
+ from sympy.core.symbol import Dummy
4
+ from sympy.testing.pytest import raises
5
+
6
+
7
+ def setup_test_printer(**kwargs):
8
+ p = CodePrinter(settings=kwargs)
9
+ p._not_supported = set()
10
+ p._number_symbols = set()
11
+ return p
12
+
13
+
14
+ def test_print_Dummy():
15
+ d = Dummy('d')
16
+ p = setup_test_printer()
17
+ assert p._print_Dummy(d) == "d_%i" % d.dummy_index
18
+
19
+ def test_print_Symbol():
20
+
21
+ x, y = symbols('x, if')
22
+
23
+ p = setup_test_printer()
24
+ assert p._print(x) == 'x'
25
+ assert p._print(y) == 'if'
26
+
27
+ p.reserved_words.update(['if'])
28
+ assert p._print(y) == 'if_'
29
+
30
+ p = setup_test_printer(error_on_reserved=True)
31
+ p.reserved_words.update(['if'])
32
+ with raises(ValueError):
33
+ p._print(y)
34
+
35
+ p = setup_test_printer(reserved_word_suffix='_He_Man')
36
+ p.reserved_words.update(['if'])
37
+ assert p._print(y) == 'if_He_Man'
38
+
39
+ def test_issue_15791():
40
+ class CrashingCodePrinter(CodePrinter):
41
+ def emptyPrinter(self, obj):
42
+ raise NotImplementedError
43
+
44
+ from sympy.matrices import (
45
+ MutableSparseMatrix,
46
+ ImmutableSparseMatrix,
47
+ )
48
+
49
+ c = CrashingCodePrinter()
50
+
51
+ # these should not silently succeed
52
+ with raises(NotImplementedError):
53
+ c.doprint(ImmutableSparseMatrix(2, 2, {}))
54
+ with raises(NotImplementedError):
55
+ c.doprint(MutableSparseMatrix(2, 2, {}))
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_conventions.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from sympy.core.function import (Derivative, Function)
4
+ from sympy.core.numbers import oo
5
+ from sympy.core.symbol import symbols
6
+ from sympy.functions.elementary.exponential import exp
7
+ from sympy.functions.elementary.trigonometric import cos
8
+ from sympy.integrals.integrals import Integral
9
+ from sympy.functions.special.bessel import besselj
10
+ from sympy.functions.special.polynomials import legendre
11
+ from sympy.functions.combinatorial.numbers import bell
12
+ from sympy.printing.conventions import split_super_sub, requires_partial
13
+ from sympy.testing.pytest import XFAIL
14
+
15
+ def test_super_sub():
16
+ assert split_super_sub("beta_13_2") == ("beta", [], ["13", "2"])
17
+ assert split_super_sub("beta_132_20") == ("beta", [], ["132", "20"])
18
+ assert split_super_sub("beta_13") == ("beta", [], ["13"])
19
+ assert split_super_sub("x_a_b") == ("x", [], ["a", "b"])
20
+ assert split_super_sub("x_1_2_3") == ("x", [], ["1", "2", "3"])
21
+ assert split_super_sub("x_a_b1") == ("x", [], ["a", "b1"])
22
+ assert split_super_sub("x_a_1") == ("x", [], ["a", "1"])
23
+ assert split_super_sub("x_1_a") == ("x", [], ["1", "a"])
24
+ assert split_super_sub("x_1^aa") == ("x", ["aa"], ["1"])
25
+ assert split_super_sub("x_1__aa") == ("x", ["aa"], ["1"])
26
+ assert split_super_sub("x_11^a") == ("x", ["a"], ["11"])
27
+ assert split_super_sub("x_11__a") == ("x", ["a"], ["11"])
28
+ assert split_super_sub("x_a_b_c_d") == ("x", [], ["a", "b", "c", "d"])
29
+ assert split_super_sub("x_a_b^c^d") == ("x", ["c", "d"], ["a", "b"])
30
+ assert split_super_sub("x_a_b__c__d") == ("x", ["c", "d"], ["a", "b"])
31
+ assert split_super_sub("x_a^b_c^d") == ("x", ["b", "d"], ["a", "c"])
32
+ assert split_super_sub("x_a__b_c__d") == ("x", ["b", "d"], ["a", "c"])
33
+ assert split_super_sub("x^a^b_c_d") == ("x", ["a", "b"], ["c", "d"])
34
+ assert split_super_sub("x__a__b_c_d") == ("x", ["a", "b"], ["c", "d"])
35
+ assert split_super_sub("x^a^b^c^d") == ("x", ["a", "b", "c", "d"], [])
36
+ assert split_super_sub("x__a__b__c__d") == ("x", ["a", "b", "c", "d"], [])
37
+ assert split_super_sub("alpha_11") == ("alpha", [], ["11"])
38
+ assert split_super_sub("alpha_11_11") == ("alpha", [], ["11", "11"])
39
+ assert split_super_sub("w1") == ("w", [], ["1"])
40
+ assert split_super_sub("w𝟙") == ("w", [], ["𝟙"])
41
+ assert split_super_sub("w11") == ("w", [], ["11"])
42
+ assert split_super_sub("w𝟙𝟙") == ("w", [], ["𝟙𝟙"])
43
+ assert split_super_sub("w𝟙2𝟙") == ("w", [], ["𝟙2𝟙"])
44
+ assert split_super_sub("w1^a") == ("w", ["a"], ["1"])
45
+ assert split_super_sub("ω1") == ("ω", [], ["1"])
46
+ assert split_super_sub("ω11") == ("ω", [], ["11"])
47
+ assert split_super_sub("ω1^a") == ("ω", ["a"], ["1"])
48
+ assert split_super_sub("ω𝟙^α") == ("ω", ["α"], ["𝟙"])
49
+ assert split_super_sub("ω𝟙2^3α") == ("ω", ["3α"], ["𝟙2"])
50
+ assert split_super_sub("") == ("", [], [])
51
+
52
+
53
+ def test_requires_partial():
54
+ x, y, z, t, nu = symbols('x y z t nu')
55
+ n = symbols('n', integer=True)
56
+
57
+ f = x * y
58
+ assert requires_partial(Derivative(f, x)) is True
59
+ assert requires_partial(Derivative(f, y)) is True
60
+
61
+ ## integrating out one of the variables
62
+ assert requires_partial(Derivative(Integral(exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False
63
+
64
+ ## bessel function with smooth parameter
65
+ f = besselj(nu, x)
66
+ assert requires_partial(Derivative(f, x)) is True
67
+ assert requires_partial(Derivative(f, nu)) is True
68
+
69
+ ## bessel function with integer parameter
70
+ f = besselj(n, x)
71
+ assert requires_partial(Derivative(f, x)) is False
72
+ # this is not really valid (differentiating with respect to an integer)
73
+ # but there's no reason to use the partial derivative symbol there. make
74
+ # sure we don't throw an exception here, though
75
+ assert requires_partial(Derivative(f, n)) is False
76
+
77
+ ## bell polynomial
78
+ f = bell(n, x)
79
+ assert requires_partial(Derivative(f, x)) is False
80
+ # again, invalid
81
+ assert requires_partial(Derivative(f, n)) is False
82
+
83
+ ## legendre polynomial
84
+ f = legendre(0, x)
85
+ assert requires_partial(Derivative(f, x)) is False
86
+
87
+ f = legendre(n, x)
88
+ assert requires_partial(Derivative(f, x)) is False
89
+ # again, invalid
90
+ assert requires_partial(Derivative(f, n)) is False
91
+
92
+ f = x ** n
93
+ assert requires_partial(Derivative(f, x)) is False
94
+
95
+ assert requires_partial(Derivative(Integral((x*y) ** n * exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False
96
+
97
+ # parametric equation
98
+ f = (exp(t), cos(t))
99
+ g = sum(f)
100
+ assert requires_partial(Derivative(g, t)) is False
101
+
102
+ f = symbols('f', cls=Function)
103
+ assert requires_partial(Derivative(f(x), x)) is False
104
+ assert requires_partial(Derivative(f(x), y)) is False
105
+ assert requires_partial(Derivative(f(x, y), x)) is True
106
+ assert requires_partial(Derivative(f(x, y), y)) is True
107
+ assert requires_partial(Derivative(f(x, y), z)) is True
108
+ assert requires_partial(Derivative(f(x, y), x, y)) is True
109
+
110
+ @XFAIL
111
+ def test_requires_partial_unspecified_variables():
112
+ x, y = symbols('x y')
113
+ # function of unspecified variables
114
+ f = symbols('f', cls=Function)
115
+ assert requires_partial(Derivative(f, x)) is False
116
+ assert requires_partial(Derivative(f, x, y)) is True
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_cupy.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.functions.elementary.exponential import log
3
+ from sympy.functions.elementary.miscellaneous import sqrt
4
+ from sympy.utilities.lambdify import lambdify
5
+ from sympy.abc import x, i, a, b
6
+ from sympy.codegen.numpy_nodes import logaddexp
7
+ from sympy.printing.numpy import CuPyPrinter, _cupy_known_constants, _cupy_known_functions
8
+
9
+ from sympy.testing.pytest import skip
10
+ from sympy.external import import_module
11
+
12
+ cp = import_module('cupy')
13
+
14
+ def test_cupy_print():
15
+ prntr = CuPyPrinter()
16
+ assert prntr.doprint(logaddexp(a, b)) == 'cupy.logaddexp(a, b)'
17
+ assert prntr.doprint(sqrt(x)) == 'cupy.sqrt(x)'
18
+ assert prntr.doprint(log(x)) == 'cupy.log(x)'
19
+ assert prntr.doprint("acos(x)") == 'cupy.arccos(x)'
20
+ assert prntr.doprint("exp(x)") == 'cupy.exp(x)'
21
+ assert prntr.doprint("Abs(x)") == 'abs(x)'
22
+
23
+ def test_not_cupy_print():
24
+ prntr = CuPyPrinter()
25
+ assert "Not supported" in prntr.doprint("abcd(x)")
26
+
27
+ def test_cupy_sum():
28
+ if not cp:
29
+ skip("CuPy not installed")
30
+
31
+ s = Sum(x ** i, (i, a, b))
32
+ f = lambdify((a, b, x), s, 'cupy')
33
+
34
+ a_, b_ = 0, 10
35
+ x_ = cp.linspace(-1, +1, 10)
36
+ assert cp.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1)))
37
+
38
+ s = Sum(i * x, (i, a, b))
39
+ f = lambdify((a, b, x), s, 'numpy')
40
+
41
+ a_, b_ = 0, 10
42
+ x_ = cp.linspace(-1, +1, 10)
43
+ assert cp.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
44
+
45
+ def test_cupy_known_funcs_consts():
46
+ assert _cupy_known_constants['NaN'] == 'cupy.nan'
47
+ assert _cupy_known_constants['EulerGamma'] == 'cupy.euler_gamma'
48
+
49
+ assert _cupy_known_functions['acos'] == 'cupy.arccos'
50
+ assert _cupy_known_functions['log'] == 'cupy.log'
51
+
52
+ def test_cupy_print_methods():
53
+ prntr = CuPyPrinter()
54
+ assert hasattr(prntr, '_print_acos')
55
+ assert hasattr(prntr, '_print_log')
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_cxx.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols
2
+ from sympy.functions import beta, Ei, zeta, Max, Min, sqrt, riemann_xi, frac
3
+ from sympy.printing.cxx import CXX98CodePrinter, CXX11CodePrinter, CXX17CodePrinter, cxxcode
4
+ from sympy.codegen.cfunctions import log1p
5
+
6
+
7
+ x, y, u, v = symbols('x y u v')
8
+
9
+
10
+ def test_CXX98CodePrinter():
11
+ assert CXX98CodePrinter().doprint(Max(x, 3)) in ('std::max(x, 3)', 'std::max(3, x)')
12
+ assert CXX98CodePrinter().doprint(Min(x, 3, sqrt(x))) == 'std::min(3, std::min(x, std::sqrt(x)))'
13
+ cxx98printer = CXX98CodePrinter()
14
+ assert cxx98printer.language == 'C++'
15
+ assert cxx98printer.standard == 'C++98'
16
+ assert 'template' in cxx98printer.reserved_words
17
+ assert 'alignas' not in cxx98printer.reserved_words
18
+
19
+
20
+ def test_CXX11CodePrinter():
21
+ assert CXX11CodePrinter().doprint(log1p(x)) == 'std::log1p(x)'
22
+
23
+ cxx11printer = CXX11CodePrinter()
24
+ assert cxx11printer.language == 'C++'
25
+ assert cxx11printer.standard == 'C++11'
26
+ assert 'operator' in cxx11printer.reserved_words
27
+ assert 'noexcept' in cxx11printer.reserved_words
28
+ assert 'concept' not in cxx11printer.reserved_words
29
+
30
+
31
+ def test_subclass_print_method():
32
+ class MyPrinter(CXX11CodePrinter):
33
+ def _print_log1p(self, expr):
34
+ return 'my_library::log1p(%s)' % ', '.join(map(self._print, expr.args))
35
+
36
+ assert MyPrinter().doprint(log1p(x)) == 'my_library::log1p(x)'
37
+
38
+
39
+ def test_subclass_print_method__ns():
40
+ class MyPrinter(CXX11CodePrinter):
41
+ _ns = 'my_library::'
42
+
43
+ p = CXX11CodePrinter()
44
+ myp = MyPrinter()
45
+
46
+ assert p.doprint(log1p(x)) == 'std::log1p(x)'
47
+ assert myp.doprint(log1p(x)) == 'my_library::log1p(x)'
48
+
49
+
50
+ def test_CXX17CodePrinter():
51
+ assert CXX17CodePrinter().doprint(beta(x, y)) == 'std::beta(x, y)'
52
+ assert CXX17CodePrinter().doprint(Ei(x)) == 'std::expint(x)'
53
+ assert CXX17CodePrinter().doprint(zeta(x)) == 'std::riemann_zeta(x)'
54
+
55
+ # Automatic rewrite
56
+ assert CXX17CodePrinter().doprint(frac(x)) == 'x - std::floor(x)'
57
+ assert CXX17CodePrinter().doprint(riemann_xi(x)) == '(1.0/2.0)*std::pow(M_PI, -1.0/2.0*x)*x*(x - 1)*std::tgamma((1.0/2.0)*x)*std::riemann_zeta(x)'
58
+
59
+
60
+ def test_cxxcode():
61
+ assert sorted(cxxcode(sqrt(x)*.5).split('*')) == sorted(['0.5', 'std::sqrt(x)'])
62
+
63
+ def test_cxxcode_nested_minmax():
64
+ assert cxxcode(Max(Min(x, y), Min(u, v))) \
65
+ == 'std::max(std::min(u, v), std::min(x, y))'
66
+ assert cxxcode(Min(Max(x, y), Max(u, v))) \
67
+ == 'std::min(std::max(u, v), std::max(x, y))'
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_dot.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.printing.dot import (purestr, styleof, attrprint, dotnode,
2
+ dotedges, dotprint)
3
+ from sympy.core.basic import Basic
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.numbers import (Float, Integer)
6
+ from sympy.core.singleton import S
7
+ from sympy.core.symbol import (Symbol, symbols)
8
+ from sympy.printing.repr import srepr
9
+ from sympy.abc import x
10
+
11
+
12
+ def test_purestr():
13
+ assert purestr(Symbol('x')) == "Symbol('x')"
14
+ assert purestr(Basic(S(1), S(2))) == "Basic(Integer(1), Integer(2))"
15
+ assert purestr(Float(2)) == "Float('2.0', precision=53)"
16
+
17
+ assert purestr(Symbol('x'), with_args=True) == ("Symbol('x')", ())
18
+ assert purestr(Basic(S(1), S(2)), with_args=True) == \
19
+ ('Basic(Integer(1), Integer(2))', ('Integer(1)', 'Integer(2)'))
20
+ assert purestr(Float(2), with_args=True) == \
21
+ ("Float('2.0', precision=53)", ())
22
+
23
+
24
+ def test_styleof():
25
+ styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}),
26
+ (Expr, {'color': 'black'})]
27
+ assert styleof(Basic(S(1)), styles) == {'color': 'blue', 'shape': 'ellipse'}
28
+
29
+ assert styleof(x + 1, styles) == {'color': 'black', 'shape': 'ellipse'}
30
+
31
+
32
+ def test_attrprint():
33
+ assert attrprint({'color': 'blue', 'shape': 'ellipse'}) == \
34
+ '"color"="blue", "shape"="ellipse"'
35
+
36
+ def test_dotnode():
37
+
38
+ assert dotnode(x, repeat=False) == \
39
+ '"Symbol(\'x\')" ["color"="black", "label"="x", "shape"="ellipse"];'
40
+ assert dotnode(x+2, repeat=False) == \
41
+ '"Add(Integer(2), Symbol(\'x\'))" ' \
42
+ '["color"="black", "label"="Add", "shape"="ellipse"];', \
43
+ dotnode(x+2,repeat=0)
44
+
45
+ assert dotnode(x + x**2, repeat=False) == \
46
+ '"Add(Symbol(\'x\'), Pow(Symbol(\'x\'), Integer(2)))" ' \
47
+ '["color"="black", "label"="Add", "shape"="ellipse"];'
48
+ assert dotnode(x + x**2, repeat=True) == \
49
+ '"Add(Symbol(\'x\'), Pow(Symbol(\'x\'), Integer(2)))_()" ' \
50
+ '["color"="black", "label"="Add", "shape"="ellipse"];'
51
+
52
+ def test_dotedges():
53
+ assert sorted(dotedges(x+2, repeat=False)) == [
54
+ '"Add(Integer(2), Symbol(\'x\'))" -> "Integer(2)";',
55
+ '"Add(Integer(2), Symbol(\'x\'))" -> "Symbol(\'x\')";'
56
+ ]
57
+ assert sorted(dotedges(x + 2, repeat=True)) == [
58
+ '"Add(Integer(2), Symbol(\'x\'))_()" -> "Integer(2)_(0,)";',
59
+ '"Add(Integer(2), Symbol(\'x\'))_()" -> "Symbol(\'x\')_(1,)";'
60
+ ]
61
+
62
+ def test_dotprint():
63
+ text = dotprint(x+2, repeat=False)
64
+ assert all(e in text for e in dotedges(x+2, repeat=False))
65
+ assert all(
66
+ n in text for n in [dotnode(expr, repeat=False)
67
+ for expr in (x, Integer(2), x+2)])
68
+ assert 'digraph' in text
69
+
70
+ text = dotprint(x+x**2, repeat=False)
71
+ assert all(e in text for e in dotedges(x+x**2, repeat=False))
72
+ assert all(
73
+ n in text for n in [dotnode(expr, repeat=False)
74
+ for expr in (x, Integer(2), x**2)])
75
+ assert 'digraph' in text
76
+
77
+ text = dotprint(x+x**2, repeat=True)
78
+ assert all(e in text for e in dotedges(x+x**2, repeat=True))
79
+ assert all(
80
+ n in text for n in [dotnode(expr, pos=())
81
+ for expr in [x + x**2]])
82
+
83
+ text = dotprint(x**x, repeat=True)
84
+ assert all(e in text for e in dotedges(x**x, repeat=True))
85
+ assert all(
86
+ n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))])
87
+ assert 'digraph' in text
88
+
89
+ def test_dotprint_depth():
90
+ text = dotprint(3*x+2, depth=1)
91
+ assert dotnode(3*x+2) in text
92
+ assert dotnode(x) not in text
93
+ text = dotprint(3*x+2)
94
+ assert "depth" not in text
95
+
96
+ def test_Matrix_and_non_basics():
97
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
98
+ n = Symbol('n')
99
+ assert dotprint(MatrixSymbol('X', n, n)) == \
100
+ """digraph{
101
+
102
+ # Graph style
103
+ "ordering"="out"
104
+ "rankdir"="TD"
105
+
106
+ #########
107
+ # Nodes #
108
+ #########
109
+
110
+ "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" ["color"="black", "label"="MatrixSymbol", "shape"="ellipse"];
111
+ "Str('X')_(0,)" ["color"="blue", "label"="X", "shape"="ellipse"];
112
+ "Symbol('n')_(1,)" ["color"="black", "label"="n", "shape"="ellipse"];
113
+ "Symbol('n')_(2,)" ["color"="black", "label"="n", "shape"="ellipse"];
114
+
115
+ #########
116
+ # Edges #
117
+ #########
118
+
119
+ "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Str('X')_(0,)";
120
+ "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(1,)";
121
+ "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(2,)";
122
+ }"""
123
+
124
+
125
+ def test_labelfunc():
126
+ text = dotprint(x + 2, labelfunc=srepr)
127
+ assert "Symbol('x')" in text
128
+ assert "Integer(2)" in text
129
+
130
+
131
+ def test_commutative():
132
+ x, y = symbols('x y', commutative=False)
133
+ assert dotprint(x + y) == dotprint(y + x)
134
+ assert dotprint(x*y) != dotprint(y*x)
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_fortran.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.expr import Expr
3
+ from sympy.core.function import (Function, Lambda, diff)
4
+ from sympy.core.mod import Mod
5
+ from sympy.core import (Catalan, EulerGamma, GoldenRatio)
6
+ from sympy.core.numbers import (E, Float, I, Integer, Rational, pi)
7
+ from sympy.core.relational import Eq
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Dummy, symbols)
10
+ from sympy.functions.combinatorial.factorials import factorial
11
+ from sympy.functions.elementary.complexes import (conjugate, sign)
12
+ from sympy.functions.elementary.exponential import (exp, log)
13
+ from sympy.functions.elementary.miscellaneous import sqrt
14
+ from sympy.functions.elementary.piecewise import Piecewise
15
+ from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
16
+ from sympy.functions.special.gamma_functions import gamma
17
+ from sympy.integrals.integrals import Integral
18
+ from sympy.sets.fancysets import Range
19
+
20
+ from sympy.codegen import For, Assignment, aug_assign
21
+ from sympy.codegen.ast import Declaration, Variable, float32, float64, \
22
+ value_const, real, bool_, While, FunctionPrototype, FunctionDefinition, \
23
+ integer, Return, Element
24
+ from sympy.core.expr import UnevaluatedExpr
25
+ from sympy.core.relational import Relational
26
+ from sympy.logic.boolalg import And, Or, Not, Equivalent, Xor
27
+ from sympy.matrices import Matrix, MatrixSymbol
28
+ from sympy.printing.fortran import fcode, FCodePrinter
29
+ from sympy.tensor import IndexedBase, Idx
30
+ from sympy.tensor.array.expressions import ArraySymbol, ArrayElement
31
+ from sympy.utilities.lambdify import implemented_function
32
+ from sympy.testing.pytest import raises
33
+
34
+
35
+ def test_UnevaluatedExpr():
36
+ p, q, r = symbols("p q r", real=True)
37
+ q_r = UnevaluatedExpr(q + r)
38
+ expr = abs(exp(p+q_r))
39
+ assert fcode(expr, source_format="free") == "exp(p + (q + r))"
40
+ x, y, z = symbols("x y z")
41
+ y_z = UnevaluatedExpr(y + z)
42
+ expr2 = abs(exp(x+y_z))
43
+ assert fcode(expr2, human=False)[2].lstrip() == "exp(re(x) + re(y + z))"
44
+ assert fcode(expr2, user_functions={"re": "realpart"}).lstrip() == "exp(realpart(x) + realpart(y + z))"
45
+
46
+
47
+ def test_printmethod():
48
+ x = symbols('x')
49
+
50
+ class nint(Function):
51
+ def _fcode(self, printer):
52
+ return "nint(%s)" % printer._print(self.args[0])
53
+ assert fcode(nint(x)) == " nint(x)"
54
+
55
+
56
+ def test_fcode_sign(): #issue 12267
57
+ x=symbols('x')
58
+ y=symbols('y', integer=True)
59
+ z=symbols('z', complex=True)
60
+ assert fcode(sign(x), standard=95, source_format='free') == "merge(0d0, dsign(1d0, x), x == 0d0)"
61
+ assert fcode(sign(y), standard=95, source_format='free') == "merge(0, isign(1, y), y == 0)"
62
+ assert fcode(sign(z), standard=95, source_format='free') == "merge(cmplx(0d0, 0d0), z/abs(z), abs(z) == 0d0)"
63
+ raises(NotImplementedError, lambda: fcode(sign(x)))
64
+
65
+
66
+ def test_fcode_Pow():
67
+ x, y = symbols('x,y')
68
+ n = symbols('n', integer=True)
69
+
70
+ assert fcode(x**3) == " x**3"
71
+ assert fcode(x**(y**3)) == " x**(y**3)"
72
+ assert fcode(1/(sin(x)*3.5)**(x - y**x)/(x**2 + y)) == \
73
+ " (3.5d0*sin(x))**(-x + y**x)/(x**2 + y)"
74
+ assert fcode(sqrt(x)) == ' sqrt(x)'
75
+ assert fcode(sqrt(n)) == ' sqrt(dble(n))'
76
+ assert fcode(x**0.5) == ' sqrt(x)'
77
+ assert fcode(sqrt(x)) == ' sqrt(x)'
78
+ assert fcode(sqrt(10)) == ' sqrt(10.0d0)'
79
+ assert fcode(x**-1.0) == ' 1d0/x'
80
+ assert fcode(x**-2.0, 'y', source_format='free') == 'y = x**(-2.0d0)' # 2823
81
+ assert fcode(x**Rational(3, 7)) == ' x**(3.0d0/7.0d0)'
82
+
83
+
84
+ def test_fcode_Rational():
85
+ x = symbols('x')
86
+ assert fcode(Rational(3, 7)) == " 3.0d0/7.0d0"
87
+ assert fcode(Rational(18, 9)) == " 2"
88
+ assert fcode(Rational(3, -7)) == " -3.0d0/7.0d0"
89
+ assert fcode(Rational(-3, -7)) == " 3.0d0/7.0d0"
90
+ assert fcode(x + Rational(3, 7)) == " x + 3.0d0/7.0d0"
91
+ assert fcode(Rational(3, 7)*x) == " (3.0d0/7.0d0)*x"
92
+
93
+
94
+ def test_fcode_Integer():
95
+ assert fcode(Integer(67)) == " 67"
96
+ assert fcode(Integer(-1)) == " -1"
97
+
98
+
99
+ def test_fcode_Float():
100
+ assert fcode(Float(42.0)) == " 42.0000000000000d0"
101
+ assert fcode(Float(-1e20)) == " -1.00000000000000d+20"
102
+
103
+
104
+ def test_fcode_functions():
105
+ x, y = symbols('x,y')
106
+ assert fcode(sin(x) ** cos(y)) == " sin(x)**cos(y)"
107
+ raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=66))
108
+ raises(NotImplementedError, lambda: fcode(x % y, standard=66))
109
+ raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=77))
110
+ raises(NotImplementedError, lambda: fcode(x % y, standard=77))
111
+ for standard in [90, 95, 2003, 2008]:
112
+ assert fcode(Mod(x, y), standard=standard) == " modulo(x, y)"
113
+ assert fcode(x % y, standard=standard) == " modulo(x, y)"
114
+
115
+
116
+ def test_case():
117
+ ob = FCodePrinter()
118
+ x,x_,x__,y,X,X_,Y = symbols('x,x_,x__,y,X,X_,Y')
119
+ assert fcode(exp(x_) + sin(x*y) + cos(X*Y)) == \
120
+ ' exp(x_) + sin(x*y) + cos(X__*Y_)'
121
+ assert fcode(exp(x__) + 2*x*Y*X_**Rational(7, 2)) == \
122
+ ' 2*X_**(7.0d0/2.0d0)*Y*x + exp(x__)'
123
+ assert fcode(exp(x_) + sin(x*y) + cos(X*Y), name_mangling=False) == \
124
+ ' exp(x_) + sin(x*y) + cos(X*Y)'
125
+ assert fcode(x - cos(X), name_mangling=False) == ' x - cos(X)'
126
+ assert ob.doprint(X*sin(x) + x_, assign_to='me') == ' me = X*sin(x_) + x__'
127
+ assert ob.doprint(X*sin(x), assign_to='mu') == ' mu = X*sin(x_)'
128
+ assert ob.doprint(x_, assign_to='ad') == ' ad = x__'
129
+ n, m = symbols('n,m', integer=True)
130
+ A = IndexedBase('A')
131
+ x = IndexedBase('x')
132
+ y = IndexedBase('y')
133
+ i = Idx('i', m)
134
+ I = Idx('I', n)
135
+ assert fcode(A[i, I]*x[I], assign_to=y[i], source_format='free') == (
136
+ "do i = 1, m\n"
137
+ " y(i) = 0\n"
138
+ "end do\n"
139
+ "do i = 1, m\n"
140
+ " do I_ = 1, n\n"
141
+ " y(i) = A(i, I_)*x(I_) + y(i)\n"
142
+ " end do\n"
143
+ "end do" )
144
+
145
+
146
+ #issue 6814
147
+ def test_fcode_functions_with_integers():
148
+ x= symbols('x')
149
+ log10_17 = log(10).evalf(17)
150
+ loglog10_17 = '0.8340324452479558d0'
151
+ assert fcode(x * log(10)) == " x*%sd0" % log10_17
152
+ assert fcode(x * log(10)) == " x*%sd0" % log10_17
153
+ assert fcode(x * log(S(10))) == " x*%sd0" % log10_17
154
+ assert fcode(log(S(10))) == " %sd0" % log10_17
155
+ assert fcode(exp(10)) == " %sd0" % exp(10).evalf(17)
156
+ assert fcode(x * log(log(10))) == " x*%s" % loglog10_17
157
+ assert fcode(x * log(log(S(10)))) == " x*%s" % loglog10_17
158
+
159
+
160
+ def test_fcode_NumberSymbol():
161
+ prec = 17
162
+ p = FCodePrinter()
163
+ assert fcode(Catalan) == ' parameter (Catalan = %sd0)\n Catalan' % Catalan.evalf(prec)
164
+ assert fcode(EulerGamma) == ' parameter (EulerGamma = %sd0)\n EulerGamma' % EulerGamma.evalf(prec)
165
+ assert fcode(E) == ' parameter (E = %sd0)\n E' % E.evalf(prec)
166
+ assert fcode(GoldenRatio) == ' parameter (GoldenRatio = %sd0)\n GoldenRatio' % GoldenRatio.evalf(prec)
167
+ assert fcode(pi) == ' parameter (pi = %sd0)\n pi' % pi.evalf(prec)
168
+ assert fcode(
169
+ pi, precision=5) == ' parameter (pi = %sd0)\n pi' % pi.evalf(5)
170
+ assert fcode(Catalan, human=False) == ({
171
+ (Catalan, p._print(Catalan.evalf(prec)))}, set(), ' Catalan')
172
+ assert fcode(EulerGamma, human=False) == ({(EulerGamma, p._print(
173
+ EulerGamma.evalf(prec)))}, set(), ' EulerGamma')
174
+ assert fcode(E, human=False) == (
175
+ {(E, p._print(E.evalf(prec)))}, set(), ' E')
176
+ assert fcode(GoldenRatio, human=False) == ({(GoldenRatio, p._print(
177
+ GoldenRatio.evalf(prec)))}, set(), ' GoldenRatio')
178
+ assert fcode(pi, human=False) == (
179
+ {(pi, p._print(pi.evalf(prec)))}, set(), ' pi')
180
+ assert fcode(pi, precision=5, human=False) == (
181
+ {(pi, p._print(pi.evalf(5)))}, set(), ' pi')
182
+
183
+
184
+ def test_fcode_complex():
185
+ assert fcode(I) == " cmplx(0,1)"
186
+ x = symbols('x')
187
+ assert fcode(4*I) == " cmplx(0,4)"
188
+ assert fcode(3 + 4*I) == " cmplx(3,4)"
189
+ assert fcode(3 + 4*I + x) == " cmplx(3,4) + x"
190
+ assert fcode(I*x) == " cmplx(0,1)*x"
191
+ assert fcode(3 + 4*I - x) == " cmplx(3,4) - x"
192
+ x = symbols('x', imaginary=True)
193
+ assert fcode(5*x) == " 5*x"
194
+ assert fcode(I*x) == " cmplx(0,1)*x"
195
+ assert fcode(3 + x) == " x + 3"
196
+
197
+
198
+ def test_implicit():
199
+ x, y = symbols('x,y')
200
+ assert fcode(sin(x)) == " sin(x)"
201
+ assert fcode(atan2(x, y)) == " atan2(x, y)"
202
+ assert fcode(conjugate(x)) == " conjg(x)"
203
+
204
+
205
+ def test_not_fortran():
206
+ x = symbols('x')
207
+ g = Function('g')
208
+ gamma_f = fcode(gamma(x))
209
+ assert gamma_f == "C Not supported in Fortran:\nC gamma\n gamma(x)"
210
+ assert fcode(Integral(sin(x))) == "C Not supported in Fortran:\nC Integral\n Integral(sin(x), x)"
211
+ assert fcode(g(x)) == "C Not supported in Fortran:\nC g\n g(x)"
212
+
213
+
214
+ def test_user_functions():
215
+ x = symbols('x')
216
+ assert fcode(sin(x), user_functions={"sin": "zsin"}) == " zsin(x)"
217
+ x = symbols('x')
218
+ assert fcode(
219
+ gamma(x), user_functions={"gamma": "mygamma"}) == " mygamma(x)"
220
+ g = Function('g')
221
+ assert fcode(g(x), user_functions={"g": "great"}) == " great(x)"
222
+ n = symbols('n', integer=True)
223
+ assert fcode(
224
+ factorial(n), user_functions={"factorial": "fct"}) == " fct(n)"
225
+
226
+
227
+ def test_inline_function():
228
+ x = symbols('x')
229
+ g = implemented_function('g', Lambda(x, 2*x))
230
+ assert fcode(g(x)) == " 2*x"
231
+ g = implemented_function('g', Lambda(x, 2*pi/x))
232
+ assert fcode(g(x)) == (
233
+ " parameter (pi = %sd0)\n"
234
+ " 2*pi/x"
235
+ ) % pi.evalf(17)
236
+ A = IndexedBase('A')
237
+ i = Idx('i', symbols('n', integer=True))
238
+ g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
239
+ assert fcode(g(A[i]), assign_to=A[i]) == (
240
+ " do i = 1, n\n"
241
+ " A(i) = (A(i) + 1)*(A(i) + 2)*A(i)\n"
242
+ " end do"
243
+ )
244
+
245
+
246
+ def test_assign_to():
247
+ x = symbols('x')
248
+ assert fcode(sin(x), assign_to="s") == " s = sin(x)"
249
+
250
+
251
+ def test_line_wrapping():
252
+ x, y = symbols('x,y')
253
+ assert fcode(((x + y)**10).expand(), assign_to="var") == (
254
+ " var = x**10 + 10*x**9*y + 45*x**8*y**2 + 120*x**7*y**3 + 210*x**6*\n"
255
+ " @ y**4 + 252*x**5*y**5 + 210*x**4*y**6 + 120*x**3*y**7 + 45*x**2*y\n"
256
+ " @ **8 + 10*x*y**9 + y**10"
257
+ )
258
+ e = [x**i for i in range(11)]
259
+ assert fcode(Add(*e)) == (
260
+ " x**10 + x**9 + x**8 + x**7 + x**6 + x**5 + x**4 + x**3 + x**2 + x\n"
261
+ " @ + 1"
262
+ )
263
+
264
+
265
+ def test_fcode_precedence():
266
+ x, y = symbols("x y")
267
+ assert fcode(And(x < y, y < x + 1), source_format="free") == \
268
+ "x < y .and. y < x + 1"
269
+ assert fcode(Or(x < y, y < x + 1), source_format="free") == \
270
+ "x < y .or. y < x + 1"
271
+ assert fcode(Xor(x < y, y < x + 1, evaluate=False),
272
+ source_format="free") == "x < y .neqv. y < x + 1"
273
+ assert fcode(Equivalent(x < y, y < x + 1), source_format="free") == \
274
+ "x < y .eqv. y < x + 1"
275
+
276
+
277
+ def test_fcode_Logical():
278
+ x, y, z = symbols("x y z")
279
+ # unary Not
280
+ assert fcode(Not(x), source_format="free") == ".not. x"
281
+ # binary And
282
+ assert fcode(And(x, y), source_format="free") == "x .and. y"
283
+ assert fcode(And(x, Not(y)), source_format="free") == "x .and. .not. y"
284
+ assert fcode(And(Not(x), y), source_format="free") == "y .and. .not. x"
285
+ assert fcode(And(Not(x), Not(y)), source_format="free") == \
286
+ ".not. x .and. .not. y"
287
+ assert fcode(Not(And(x, y), evaluate=False), source_format="free") == \
288
+ ".not. (x .and. y)"
289
+ # binary Or
290
+ assert fcode(Or(x, y), source_format="free") == "x .or. y"
291
+ assert fcode(Or(x, Not(y)), source_format="free") == "x .or. .not. y"
292
+ assert fcode(Or(Not(x), y), source_format="free") == "y .or. .not. x"
293
+ assert fcode(Or(Not(x), Not(y)), source_format="free") == \
294
+ ".not. x .or. .not. y"
295
+ assert fcode(Not(Or(x, y), evaluate=False), source_format="free") == \
296
+ ".not. (x .or. y)"
297
+ # mixed And/Or
298
+ assert fcode(And(Or(y, z), x), source_format="free") == "x .and. (y .or. z)"
299
+ assert fcode(And(Or(z, x), y), source_format="free") == "y .and. (x .or. z)"
300
+ assert fcode(And(Or(x, y), z), source_format="free") == "z .and. (x .or. y)"
301
+ assert fcode(Or(And(y, z), x), source_format="free") == "x .or. y .and. z"
302
+ assert fcode(Or(And(z, x), y), source_format="free") == "y .or. x .and. z"
303
+ assert fcode(Or(And(x, y), z), source_format="free") == "z .or. x .and. y"
304
+ # trinary And
305
+ assert fcode(And(x, y, z), source_format="free") == "x .and. y .and. z"
306
+ assert fcode(And(x, y, Not(z)), source_format="free") == \
307
+ "x .and. y .and. .not. z"
308
+ assert fcode(And(x, Not(y), z), source_format="free") == \
309
+ "x .and. z .and. .not. y"
310
+ assert fcode(And(Not(x), y, z), source_format="free") == \
311
+ "y .and. z .and. .not. x"
312
+ assert fcode(Not(And(x, y, z), evaluate=False), source_format="free") == \
313
+ ".not. (x .and. y .and. z)"
314
+ # trinary Or
315
+ assert fcode(Or(x, y, z), source_format="free") == "x .or. y .or. z"
316
+ assert fcode(Or(x, y, Not(z)), source_format="free") == \
317
+ "x .or. y .or. .not. z"
318
+ assert fcode(Or(x, Not(y), z), source_format="free") == \
319
+ "x .or. z .or. .not. y"
320
+ assert fcode(Or(Not(x), y, z), source_format="free") == \
321
+ "y .or. z .or. .not. x"
322
+ assert fcode(Not(Or(x, y, z), evaluate=False), source_format="free") == \
323
+ ".not. (x .or. y .or. z)"
324
+
325
+
326
+ def test_fcode_Xlogical():
327
+ x, y, z = symbols("x y z")
328
+ # binary Xor
329
+ assert fcode(Xor(x, y, evaluate=False), source_format="free") == \
330
+ "x .neqv. y"
331
+ assert fcode(Xor(x, Not(y), evaluate=False), source_format="free") == \
332
+ "x .neqv. .not. y"
333
+ assert fcode(Xor(Not(x), y, evaluate=False), source_format="free") == \
334
+ "y .neqv. .not. x"
335
+ assert fcode(Xor(Not(x), Not(y), evaluate=False),
336
+ source_format="free") == ".not. x .neqv. .not. y"
337
+ assert fcode(Not(Xor(x, y, evaluate=False), evaluate=False),
338
+ source_format="free") == ".not. (x .neqv. y)"
339
+ # binary Equivalent
340
+ assert fcode(Equivalent(x, y), source_format="free") == "x .eqv. y"
341
+ assert fcode(Equivalent(x, Not(y)), source_format="free") == \
342
+ "x .eqv. .not. y"
343
+ assert fcode(Equivalent(Not(x), y), source_format="free") == \
344
+ "y .eqv. .not. x"
345
+ assert fcode(Equivalent(Not(x), Not(y)), source_format="free") == \
346
+ ".not. x .eqv. .not. y"
347
+ assert fcode(Not(Equivalent(x, y), evaluate=False),
348
+ source_format="free") == ".not. (x .eqv. y)"
349
+ # mixed And/Equivalent
350
+ assert fcode(Equivalent(And(y, z), x), source_format="free") == \
351
+ "x .eqv. y .and. z"
352
+ assert fcode(Equivalent(And(z, x), y), source_format="free") == \
353
+ "y .eqv. x .and. z"
354
+ assert fcode(Equivalent(And(x, y), z), source_format="free") == \
355
+ "z .eqv. x .and. y"
356
+ assert fcode(And(Equivalent(y, z), x), source_format="free") == \
357
+ "x .and. (y .eqv. z)"
358
+ assert fcode(And(Equivalent(z, x), y), source_format="free") == \
359
+ "y .and. (x .eqv. z)"
360
+ assert fcode(And(Equivalent(x, y), z), source_format="free") == \
361
+ "z .and. (x .eqv. y)"
362
+ # mixed Or/Equivalent
363
+ assert fcode(Equivalent(Or(y, z), x), source_format="free") == \
364
+ "x .eqv. y .or. z"
365
+ assert fcode(Equivalent(Or(z, x), y), source_format="free") == \
366
+ "y .eqv. x .or. z"
367
+ assert fcode(Equivalent(Or(x, y), z), source_format="free") == \
368
+ "z .eqv. x .or. y"
369
+ assert fcode(Or(Equivalent(y, z), x), source_format="free") == \
370
+ "x .or. (y .eqv. z)"
371
+ assert fcode(Or(Equivalent(z, x), y), source_format="free") == \
372
+ "y .or. (x .eqv. z)"
373
+ assert fcode(Or(Equivalent(x, y), z), source_format="free") == \
374
+ "z .or. (x .eqv. y)"
375
+ # mixed Xor/Equivalent
376
+ assert fcode(Equivalent(Xor(y, z, evaluate=False), x),
377
+ source_format="free") == "x .eqv. (y .neqv. z)"
378
+ assert fcode(Equivalent(Xor(z, x, evaluate=False), y),
379
+ source_format="free") == "y .eqv. (x .neqv. z)"
380
+ assert fcode(Equivalent(Xor(x, y, evaluate=False), z),
381
+ source_format="free") == "z .eqv. (x .neqv. y)"
382
+ assert fcode(Xor(Equivalent(y, z), x, evaluate=False),
383
+ source_format="free") == "x .neqv. (y .eqv. z)"
384
+ assert fcode(Xor(Equivalent(z, x), y, evaluate=False),
385
+ source_format="free") == "y .neqv. (x .eqv. z)"
386
+ assert fcode(Xor(Equivalent(x, y), z, evaluate=False),
387
+ source_format="free") == "z .neqv. (x .eqv. y)"
388
+ # mixed And/Xor
389
+ assert fcode(Xor(And(y, z), x, evaluate=False), source_format="free") == \
390
+ "x .neqv. y .and. z"
391
+ assert fcode(Xor(And(z, x), y, evaluate=False), source_format="free") == \
392
+ "y .neqv. x .and. z"
393
+ assert fcode(Xor(And(x, y), z, evaluate=False), source_format="free") == \
394
+ "z .neqv. x .and. y"
395
+ assert fcode(And(Xor(y, z, evaluate=False), x), source_format="free") == \
396
+ "x .and. (y .neqv. z)"
397
+ assert fcode(And(Xor(z, x, evaluate=False), y), source_format="free") == \
398
+ "y .and. (x .neqv. z)"
399
+ assert fcode(And(Xor(x, y, evaluate=False), z), source_format="free") == \
400
+ "z .and. (x .neqv. y)"
401
+ # mixed Or/Xor
402
+ assert fcode(Xor(Or(y, z), x, evaluate=False), source_format="free") == \
403
+ "x .neqv. y .or. z"
404
+ assert fcode(Xor(Or(z, x), y, evaluate=False), source_format="free") == \
405
+ "y .neqv. x .or. z"
406
+ assert fcode(Xor(Or(x, y), z, evaluate=False), source_format="free") == \
407
+ "z .neqv. x .or. y"
408
+ assert fcode(Or(Xor(y, z, evaluate=False), x), source_format="free") == \
409
+ "x .or. (y .neqv. z)"
410
+ assert fcode(Or(Xor(z, x, evaluate=False), y), source_format="free") == \
411
+ "y .or. (x .neqv. z)"
412
+ assert fcode(Or(Xor(x, y, evaluate=False), z), source_format="free") == \
413
+ "z .or. (x .neqv. y)"
414
+ # trinary Xor
415
+ assert fcode(Xor(x, y, z, evaluate=False), source_format="free") == \
416
+ "x .neqv. y .neqv. z"
417
+ assert fcode(Xor(x, y, Not(z), evaluate=False), source_format="free") == \
418
+ "x .neqv. y .neqv. .not. z"
419
+ assert fcode(Xor(x, Not(y), z, evaluate=False), source_format="free") == \
420
+ "x .neqv. z .neqv. .not. y"
421
+ assert fcode(Xor(Not(x), y, z, evaluate=False), source_format="free") == \
422
+ "y .neqv. z .neqv. .not. x"
423
+
424
+
425
+ def test_fcode_Relational():
426
+ x, y = symbols("x y")
427
+ assert fcode(Relational(x, y, "=="), source_format="free") == "x == y"
428
+ assert fcode(Relational(x, y, "!="), source_format="free") == "x /= y"
429
+ assert fcode(Relational(x, y, ">="), source_format="free") == "x >= y"
430
+ assert fcode(Relational(x, y, "<="), source_format="free") == "x <= y"
431
+ assert fcode(Relational(x, y, ">"), source_format="free") == "x > y"
432
+ assert fcode(Relational(x, y, "<"), source_format="free") == "x < y"
433
+
434
+
435
+ def test_fcode_Piecewise():
436
+ x = symbols('x')
437
+ expr = Piecewise((x, x < 1), (x**2, True))
438
+ # Check that inline conditional (merge) fails if standard isn't 95+
439
+ raises(NotImplementedError, lambda: fcode(expr))
440
+ code = fcode(expr, standard=95)
441
+ expected = " merge(x, x**2, x < 1)"
442
+ assert code == expected
443
+ assert fcode(Piecewise((x, x < 1), (x**2, True)), assign_to="var") == (
444
+ " if (x < 1) then\n"
445
+ " var = x\n"
446
+ " else\n"
447
+ " var = x**2\n"
448
+ " end if"
449
+ )
450
+ a = cos(x)/x
451
+ b = sin(x)/x
452
+ for i in range(10):
453
+ a = diff(a, x)
454
+ b = diff(b, x)
455
+ expected = (
456
+ " if (x < 0) then\n"
457
+ " weird_name = -cos(x)/x + 10*sin(x)/x**2 + 90*cos(x)/x**3 - 720*\n"
458
+ " @ sin(x)/x**4 - 5040*cos(x)/x**5 + 30240*sin(x)/x**6 + 151200*cos(x\n"
459
+ " @ )/x**7 - 604800*sin(x)/x**8 - 1814400*cos(x)/x**9 + 3628800*sin(x\n"
460
+ " @ )/x**10 + 3628800*cos(x)/x**11\n"
461
+ " else\n"
462
+ " weird_name = -sin(x)/x - 10*cos(x)/x**2 + 90*sin(x)/x**3 + 720*\n"
463
+ " @ cos(x)/x**4 - 5040*sin(x)/x**5 - 30240*cos(x)/x**6 + 151200*sin(x\n"
464
+ " @ )/x**7 + 604800*cos(x)/x**8 - 1814400*sin(x)/x**9 - 3628800*cos(x\n"
465
+ " @ )/x**10 + 3628800*sin(x)/x**11\n"
466
+ " end if"
467
+ )
468
+ code = fcode(Piecewise((a, x < 0), (b, True)), assign_to="weird_name")
469
+ assert code == expected
470
+ code = fcode(Piecewise((x, x < 1), (x**2, x > 1), (sin(x), True)), standard=95)
471
+ expected = " merge(x, merge(x**2, sin(x), x > 1), x < 1)"
472
+ assert code == expected
473
+ # Check that Piecewise without a True (default) condition error
474
+ expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
475
+ raises(ValueError, lambda: fcode(expr))
476
+
477
+
478
+ def test_wrap_fortran():
479
+ # "########################################################################"
480
+ printer = FCodePrinter()
481
+ lines = [
482
+ "C This is a long comment on a single line that must be wrapped properly to produce nice output",
483
+ " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly",
484
+ " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly",
485
+ " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly",
486
+ " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
487
+ " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
488
+ " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
489
+ " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
490
+ " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
491
+ " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
492
+ " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
493
+ " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
494
+ " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
495
+ " this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly",
496
+ " this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly",
497
+ ]
498
+ wrapped_lines = printer._wrap_fortran(lines)
499
+ expected_lines = [
500
+ "C This is a long comment on a single line that must be wrapped",
501
+ "C properly to produce nice output",
502
+ " this = is + a + long + and + nasty + fortran + statement + that *",
503
+ " @ must + be + wrapped + properly",
504
+ " this = is + a + long + and + nasty + fortran + statement + that *",
505
+ " @ must + be + wrapped + properly",
506
+ " this = is + a + long + and + nasty + fortran + statement + that",
507
+ " @ * must + be + wrapped + properly",
508
+ " this = is + a + long + and + nasty + fortran + statement + that*",
509
+ " @ must + be + wrapped + properly",
510
+ " this = is + a + long + and + nasty + fortran + statement + that*",
511
+ " @ must + be + wrapped + properly",
512
+ " this = is + a + long + and + nasty + fortran + statement + that",
513
+ " @ *must + be + wrapped + properly",
514
+ " this = is + a + long + and + nasty + fortran + statement +",
515
+ " @ that*must + be + wrapped + properly",
516
+ " this = is + a + long + and + nasty + fortran + statement + that**",
517
+ " @ must + be + wrapped + properly",
518
+ " this = is + a + long + and + nasty + fortran + statement + that**",
519
+ " @ must + be + wrapped + properly",
520
+ " this = is + a + long + and + nasty + fortran + statement + that",
521
+ " @ **must + be + wrapped + properly",
522
+ " this = is + a + long + and + nasty + fortran + statement + that",
523
+ " @ **must + be + wrapped + properly",
524
+ " this = is + a + long + and + nasty + fortran + statement +",
525
+ " @ that**must + be + wrapped + properly",
526
+ " this = is + a + long + and + nasty + fortran + statement(that)/",
527
+ " @ must + be + wrapped + properly",
528
+ " this = is + a + long + and + nasty + fortran + statement(that)",
529
+ " @ /must + be + wrapped + properly",
530
+ ]
531
+ for line in wrapped_lines:
532
+ assert len(line) <= 72
533
+ for w, e in zip(wrapped_lines, expected_lines):
534
+ assert w == e
535
+ assert len(wrapped_lines) == len(expected_lines)
536
+
537
+
538
+ def test_wrap_fortran_keep_d0():
539
+ printer = FCodePrinter()
540
+ lines = [
541
+ ' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0',
542
+ ' this_variable_is_very_long_because_we_try_to_test_line_break =1.0d0',
543
+ ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0',
544
+ ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0',
545
+ ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0',
546
+ ' this_variable_is_very_long_because_we_try_to_test_line_break = 10.0d0'
547
+ ]
548
+ expected = [
549
+ ' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0',
550
+ ' this_variable_is_very_long_because_we_try_to_test_line_break =',
551
+ ' @ 1.0d0',
552
+ ' this_variable_is_very_long_because_we_try_to_test_line_break =',
553
+ ' @ 1.0d0',
554
+ ' this_variable_is_very_long_because_we_try_to_test_line_break =',
555
+ ' @ 1.0d0',
556
+ ' this_variable_is_very_long_because_we_try_to_test_line_break =',
557
+ ' @ 1.0d0',
558
+ ' this_variable_is_very_long_because_we_try_to_test_line_break =',
559
+ ' @ 10.0d0'
560
+ ]
561
+ assert printer._wrap_fortran(lines) == expected
562
+
563
+
564
+ def test_settings():
565
+ raises(TypeError, lambda: fcode(S(4), method="garbage"))
566
+
567
+
568
+ def test_free_form_code_line():
569
+ x, y = symbols('x,y')
570
+ assert fcode(cos(x) + sin(y), source_format='free') == "sin(y) + cos(x)"
571
+
572
+
573
+ def test_free_form_continuation_line():
574
+ x, y = symbols('x,y')
575
+ result = fcode(((cos(x) + sin(y))**(7)).expand(), source_format='free')
576
+ expected = (
577
+ 'sin(y)**7 + 7*sin(y)**6*cos(x) + 21*sin(y)**5*cos(x)**2 + 35*sin(y)**4* &\n'
578
+ ' cos(x)**3 + 35*sin(y)**3*cos(x)**4 + 21*sin(y)**2*cos(x)**5 + 7* &\n'
579
+ ' sin(y)*cos(x)**6 + cos(x)**7'
580
+ )
581
+ assert result == expected
582
+
583
+
584
+ def test_free_form_comment_line():
585
+ printer = FCodePrinter({'source_format': 'free'})
586
+ lines = [ "! This is a long comment on a single line that must be wrapped properly to produce nice output"]
587
+ expected = [
588
+ '! This is a long comment on a single line that must be wrapped properly',
589
+ '! to produce nice output']
590
+ assert printer._wrap_fortran(lines) == expected
591
+
592
+
593
+ def test_loops():
594
+ n, m = symbols('n,m', integer=True)
595
+ A = IndexedBase('A')
596
+ x = IndexedBase('x')
597
+ y = IndexedBase('y')
598
+ i = Idx('i', m)
599
+ j = Idx('j', n)
600
+
601
+ expected = (
602
+ 'do i = 1, m\n'
603
+ ' y(i) = 0\n'
604
+ 'end do\n'
605
+ 'do i = 1, m\n'
606
+ ' do j = 1, n\n'
607
+ ' y(i) = %(rhs)s\n'
608
+ ' end do\n'
609
+ 'end do'
610
+ )
611
+
612
+ code = fcode(A[i, j]*x[j], assign_to=y[i], source_format='free')
613
+ assert (code == expected % {'rhs': 'y(i) + A(i, j)*x(j)'} or
614
+ code == expected % {'rhs': 'y(i) + x(j)*A(i, j)'} or
615
+ code == expected % {'rhs': 'x(j)*A(i, j) + y(i)'} or
616
+ code == expected % {'rhs': 'A(i, j)*x(j) + y(i)'})
617
+
618
+
619
+ def test_dummy_loops():
620
+ i, m = symbols('i m', integer=True, cls=Dummy)
621
+ x = IndexedBase('x')
622
+ y = IndexedBase('y')
623
+ i = Idx(i, m)
624
+
625
+ expected = (
626
+ 'do i_%(icount)i = 1, m_%(mcount)i\n'
627
+ ' y(i_%(icount)i) = x(i_%(icount)i)\n'
628
+ 'end do'
629
+ ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
630
+ code = fcode(x[i], assign_to=y[i], source_format='free')
631
+ assert code == expected
632
+
633
+
634
+ def test_fcode_Indexed_without_looking_for_contraction():
635
+ len_y = 5
636
+ y = IndexedBase('y', shape=(len_y,))
637
+ x = IndexedBase('x', shape=(len_y,))
638
+ Dy = IndexedBase('Dy', shape=(len_y-1,))
639
+ i = Idx('i', len_y-1)
640
+ e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
641
+ code0 = fcode(e.rhs, assign_to=e.lhs, contract=False)
642
+ assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
643
+
644
+
645
+ def test_element_like_objects():
646
+ len_y = 5
647
+ y = ArraySymbol('y', shape=(len_y,))
648
+ x = ArraySymbol('x', shape=(len_y,))
649
+ Dy = ArraySymbol('Dy', shape=(len_y-1,))
650
+ i = Idx('i', len_y-1)
651
+ e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
652
+ code0 = fcode(Assignment(e.lhs, e.rhs))
653
+ assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
654
+
655
+ class ElementExpr(Element, Expr):
656
+ pass
657
+
658
+ e = e.subs((a, ElementExpr(a.name, a.indices)) for a in e.atoms(ArrayElement) )
659
+ e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
660
+ code0 = fcode(Assignment(e.lhs, e.rhs))
661
+ assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
662
+
663
+
664
+ def test_derived_classes():
665
+ class MyFancyFCodePrinter(FCodePrinter):
666
+ _default_settings = FCodePrinter._default_settings.copy()
667
+
668
+ printer = MyFancyFCodePrinter()
669
+ x = symbols('x')
670
+ assert printer.doprint(sin(x), "bork") == " bork = sin(x)"
671
+
672
+
673
+ def test_indent():
674
+ codelines = (
675
+ 'subroutine test(a)\n'
676
+ 'integer :: a, i, j\n'
677
+ '\n'
678
+ 'do\n'
679
+ 'do \n'
680
+ 'do j = 1, 5\n'
681
+ 'if (a>b) then\n'
682
+ 'if(b>0) then\n'
683
+ 'a = 3\n'
684
+ 'donot_indent_me = 2\n'
685
+ 'do_not_indent_me_either = 2\n'
686
+ 'ifIam_indented_something_went_wrong = 2\n'
687
+ 'if_I_am_indented_something_went_wrong = 2\n'
688
+ 'end should not be unindented here\n'
689
+ 'end if\n'
690
+ 'endif\n'
691
+ 'end do\n'
692
+ 'end do\n'
693
+ 'enddo\n'
694
+ 'end subroutine\n'
695
+ '\n'
696
+ 'subroutine test2(a)\n'
697
+ 'integer :: a\n'
698
+ 'do\n'
699
+ 'a = a + 1\n'
700
+ 'end do \n'
701
+ 'end subroutine\n'
702
+ )
703
+ expected = (
704
+ 'subroutine test(a)\n'
705
+ 'integer :: a, i, j\n'
706
+ '\n'
707
+ 'do\n'
708
+ ' do \n'
709
+ ' do j = 1, 5\n'
710
+ ' if (a>b) then\n'
711
+ ' if(b>0) then\n'
712
+ ' a = 3\n'
713
+ ' donot_indent_me = 2\n'
714
+ ' do_not_indent_me_either = 2\n'
715
+ ' ifIam_indented_something_went_wrong = 2\n'
716
+ ' if_I_am_indented_something_went_wrong = 2\n'
717
+ ' end should not be unindented here\n'
718
+ ' end if\n'
719
+ ' endif\n'
720
+ ' end do\n'
721
+ ' end do\n'
722
+ 'enddo\n'
723
+ 'end subroutine\n'
724
+ '\n'
725
+ 'subroutine test2(a)\n'
726
+ 'integer :: a\n'
727
+ 'do\n'
728
+ ' a = a + 1\n'
729
+ 'end do \n'
730
+ 'end subroutine\n'
731
+ )
732
+ p = FCodePrinter({'source_format': 'free'})
733
+ result = p.indent_code(codelines)
734
+ assert result == expected
735
+
736
+ def test_Matrix_printing():
737
+ x, y, z = symbols('x,y,z')
738
+ # Test returning a Matrix
739
+ mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
740
+ A = MatrixSymbol('A', 3, 1)
741
+ assert fcode(mat, A) == (
742
+ " A(1, 1) = x*y\n"
743
+ " if (y > 0) then\n"
744
+ " A(2, 1) = x + 2\n"
745
+ " else\n"
746
+ " A(2, 1) = y\n"
747
+ " end if\n"
748
+ " A(3, 1) = sin(z)")
749
+ # Test using MatrixElements in expressions
750
+ expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
751
+ assert fcode(expr, standard=95) == (
752
+ " merge(2*A(3, 1), A(3, 1), x > 0) + sin(A(2, 1)) + A(1, 1)")
753
+ # Test using MatrixElements in a Matrix
754
+ q = MatrixSymbol('q', 5, 1)
755
+ M = MatrixSymbol('M', 3, 3)
756
+ m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
757
+ [q[1,0] + q[2,0], q[3, 0], 5],
758
+ [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
759
+ assert fcode(m, M) == (
760
+ " M(1, 1) = sin(q(2, 1))\n"
761
+ " M(2, 1) = q(2, 1) + q(3, 1)\n"
762
+ " M(3, 1) = 2*q(5, 1)/q(2, 1)\n"
763
+ " M(1, 2) = 0\n"
764
+ " M(2, 2) = q(4, 1)\n"
765
+ " M(3, 2) = sqrt(q(1, 1)) + 4\n"
766
+ " M(1, 3) = cos(q(3, 1))\n"
767
+ " M(2, 3) = 5\n"
768
+ " M(3, 3) = 0")
769
+
770
+
771
+ def test_fcode_For():
772
+ x, y = symbols('x y')
773
+
774
+ f = For(x, Range(0, 10, 2), [Assignment(y, x * y)])
775
+ sol = fcode(f)
776
+ assert sol == (" do x = 0, 9, 2\n"
777
+ " y = x*y\n"
778
+ " end do")
779
+
780
+
781
+ def test_fcode_Declaration():
782
+ def check(expr, ref, **kwargs):
783
+ assert fcode(expr, standard=95, source_format='free', **kwargs) == ref
784
+
785
+ i = symbols('i', integer=True)
786
+ var1 = Variable.deduced(i)
787
+ dcl1 = Declaration(var1)
788
+ check(dcl1, "integer*4 :: i")
789
+
790
+
791
+ x, y = symbols('x y')
792
+ var2 = Variable(x, float32, value=42, attrs={value_const})
793
+ dcl2b = Declaration(var2)
794
+ check(dcl2b, 'real*4, parameter :: x = 42')
795
+
796
+ var3 = Variable(y, type=bool_)
797
+ dcl3 = Declaration(var3)
798
+ check(dcl3, 'logical :: y')
799
+
800
+ check(float32, "real*4")
801
+ check(float64, "real*8")
802
+ check(real, "real*4", type_aliases={real: float32})
803
+ check(real, "real*8", type_aliases={real: float64})
804
+
805
+
806
+ def test_MatrixElement_printing():
807
+ # test cases for issue #11821
808
+ A = MatrixSymbol("A", 1, 3)
809
+ B = MatrixSymbol("B", 1, 3)
810
+ C = MatrixSymbol("C", 1, 3)
811
+
812
+ assert(fcode(A[0, 0]) == " A(1, 1)")
813
+ assert(fcode(3 * A[0, 0]) == " 3*A(1, 1)")
814
+
815
+ F = C[0, 0].subs(C, A - B)
816
+ assert(fcode(F) == " (A - B)(1, 1)")
817
+
818
+
819
+ def test_aug_assign():
820
+ x = symbols('x')
821
+ assert fcode(aug_assign(x, '+', 1), source_format='free') == 'x = x + 1'
822
+
823
+
824
+ def test_While():
825
+ x = symbols('x')
826
+ assert fcode(While(abs(x) > 1, [aug_assign(x, '-', 1)]), source_format='free') == (
827
+ 'do while (abs(x) > 1)\n'
828
+ ' x = x - 1\n'
829
+ 'end do'
830
+ )
831
+
832
+
833
+ def test_FunctionPrototype_print():
834
+ x = symbols('x')
835
+ n = symbols('n', integer=True)
836
+ vx = Variable(x, type=real)
837
+ vn = Variable(n, type=integer)
838
+ fp1 = FunctionPrototype(real, 'power', [vx, vn])
839
+ # Should be changed to proper test once multi-line generation is working
840
+ # see https://github.com/sympy/sympy/issues/15824
841
+ raises(NotImplementedError, lambda: fcode(fp1))
842
+
843
+
844
+ def test_FunctionDefinition_print():
845
+ x = symbols('x')
846
+ n = symbols('n', integer=True)
847
+ vx = Variable(x, type=real)
848
+ vn = Variable(n, type=integer)
849
+ body = [Assignment(x, x**n), Return(x)]
850
+ fd1 = FunctionDefinition(real, 'power', [vx, vn], body)
851
+ # Should be changed to proper test once multi-line generation is working
852
+ # see https://github.com/sympy/sympy/issues/15824
853
+ raises(NotImplementedError, lambda: fcode(fd1))
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_glsl.py ADDED
@@ -0,0 +1,998 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import (pi, symbols, Rational, Integer, GoldenRatio, EulerGamma,
2
+ Catalan, Lambda, Dummy, Eq, Ne, Le, Lt, Gt, Ge)
3
+ from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt
4
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
5
+ from sympy.printing.glsl import GLSLPrinter
6
+ from sympy.printing.str import StrPrinter
7
+ from sympy.utilities.lambdify import implemented_function
8
+ from sympy.tensor import IndexedBase, Idx
9
+ from sympy.matrices import Matrix, MatrixSymbol
10
+ from sympy.core import Tuple
11
+ from sympy.printing.glsl import glsl_code
12
+ import textwrap
13
+
14
+ x, y, z = symbols('x,y,z')
15
+
16
+
17
+ def test_printmethod():
18
+ assert glsl_code(Abs(x)) == "abs(x)"
19
+
20
+ def test_print_without_operators():
21
+ assert glsl_code(x*y,use_operators = False) == 'mul(x, y)'
22
+ assert glsl_code(x**y+z,use_operators = False) == 'add(pow(x, y), z)'
23
+ assert glsl_code(x*(y+z),use_operators = False) == 'mul(x, add(y, z))'
24
+ assert glsl_code(x*(y+z),use_operators = False) == 'mul(x, add(y, z))'
25
+ assert glsl_code(x*(y+z**y**0.5),use_operators = False) == 'mul(x, add(y, pow(z, sqrt(y))))'
26
+ assert glsl_code(-x-y, use_operators=False, zero='zero()') == 'sub(zero(), add(x, y))'
27
+ assert glsl_code(-x-y, use_operators=False) == 'sub(0.0, add(x, y))'
28
+
29
+ def test_glsl_code_sqrt():
30
+ assert glsl_code(sqrt(x)) == "sqrt(x)"
31
+ assert glsl_code(x**0.5) == "sqrt(x)"
32
+ assert glsl_code(sqrt(x)) == "sqrt(x)"
33
+
34
+
35
+ def test_glsl_code_Pow():
36
+ g = implemented_function('g', Lambda(x, 2*x))
37
+ assert glsl_code(x**3) == "pow(x, 3.0)"
38
+ assert glsl_code(x**(y**3)) == "pow(x, pow(y, 3.0))"
39
+ assert glsl_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
40
+ "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2.0) + y)"
41
+ assert glsl_code(x**-1.0) == '1.0/x'
42
+
43
+
44
+ def test_glsl_code_Relational():
45
+ assert glsl_code(Eq(x, y)) == "x == y"
46
+ assert glsl_code(Ne(x, y)) == "x != y"
47
+ assert glsl_code(Le(x, y)) == "x <= y"
48
+ assert glsl_code(Lt(x, y)) == "x < y"
49
+ assert glsl_code(Gt(x, y)) == "x > y"
50
+ assert glsl_code(Ge(x, y)) == "x >= y"
51
+
52
+
53
+ def test_glsl_code_constants_mathh():
54
+ assert glsl_code(exp(1)) == "float E = 2.71828183;\nE"
55
+ assert glsl_code(pi) == "float pi = 3.14159265;\npi"
56
+ # assert glsl_code(oo) == "Number.POSITIVE_INFINITY"
57
+ # assert glsl_code(-oo) == "Number.NEGATIVE_INFINITY"
58
+
59
+
60
+ def test_glsl_code_constants_other():
61
+ assert glsl_code(2*GoldenRatio) == "float GoldenRatio = 1.61803399;\n2*GoldenRatio"
62
+ assert glsl_code(2*Catalan) == "float Catalan = 0.915965594;\n2*Catalan"
63
+ assert glsl_code(2*EulerGamma) == "float EulerGamma = 0.577215665;\n2*EulerGamma"
64
+
65
+
66
+ def test_glsl_code_Rational():
67
+ assert glsl_code(Rational(3, 7)) == "3.0/7.0"
68
+ assert glsl_code(Rational(18, 9)) == "2"
69
+ assert glsl_code(Rational(3, -7)) == "-3.0/7.0"
70
+ assert glsl_code(Rational(-3, -7)) == "3.0/7.0"
71
+
72
+
73
+ def test_glsl_code_Integer():
74
+ assert glsl_code(Integer(67)) == "67"
75
+ assert glsl_code(Integer(-1)) == "-1"
76
+
77
+
78
+ def test_glsl_code_functions():
79
+ assert glsl_code(sin(x) ** cos(x)) == "pow(sin(x), cos(x))"
80
+
81
+
82
+ def test_glsl_code_inline_function():
83
+ x = symbols('x')
84
+ g = implemented_function('g', Lambda(x, 2*x))
85
+ assert glsl_code(g(x)) == "2*x"
86
+ g = implemented_function('g', Lambda(x, 2*x/Catalan))
87
+ assert glsl_code(g(x)) == "float Catalan = 0.915965594;\n2*x/Catalan"
88
+ A = IndexedBase('A')
89
+ i = Idx('i', symbols('n', integer=True))
90
+ g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
91
+ assert glsl_code(g(A[i]), assign_to=A[i]) == (
92
+ "for (int i=0; i<n; i++){\n"
93
+ " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
94
+ "}"
95
+ )
96
+
97
+
98
+ def test_glsl_code_exceptions():
99
+ assert glsl_code(ceiling(x)) == "ceil(x)"
100
+ assert glsl_code(Abs(x)) == "abs(x)"
101
+
102
+
103
+ def test_glsl_code_boolean():
104
+ assert glsl_code(x & y) == "x && y"
105
+ assert glsl_code(x | y) == "x || y"
106
+ assert glsl_code(~x) == "!x"
107
+ assert glsl_code(x & y & z) == "x && y && z"
108
+ assert glsl_code(x | y | z) == "x || y || z"
109
+ assert glsl_code((x & y) | z) == "z || x && y"
110
+ assert glsl_code((x | y) & z) == "z && (x || y)"
111
+
112
+
113
+ def test_glsl_code_Piecewise():
114
+ expr = Piecewise((x, x < 1), (x**2, True))
115
+ p = glsl_code(expr)
116
+ s = \
117
+ """\
118
+ ((x < 1) ? (
119
+ x
120
+ )
121
+ : (
122
+ pow(x, 2.0)
123
+ ))\
124
+ """
125
+ assert p == s
126
+ assert glsl_code(expr, assign_to="c") == (
127
+ "if (x < 1) {\n"
128
+ " c = x;\n"
129
+ "}\n"
130
+ "else {\n"
131
+ " c = pow(x, 2.0);\n"
132
+ "}")
133
+ # Check that Piecewise without a True (default) condition error
134
+ expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
135
+ raises(ValueError, lambda: glsl_code(expr))
136
+
137
+
138
+ def test_glsl_code_Piecewise_deep():
139
+ p = glsl_code(2*Piecewise((x, x < 1), (x**2, True)))
140
+ s = \
141
+ """\
142
+ 2*((x < 1) ? (
143
+ x
144
+ )
145
+ : (
146
+ pow(x, 2.0)
147
+ ))\
148
+ """
149
+ assert p == s
150
+
151
+
152
+ def test_glsl_code_settings():
153
+ raises(TypeError, lambda: glsl_code(sin(x), method="garbage"))
154
+
155
+
156
+ def test_glsl_code_Indexed():
157
+ n, m, o = symbols('n m o', integer=True)
158
+ i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
159
+ p = GLSLPrinter()
160
+ p._not_c = set()
161
+
162
+ x = IndexedBase('x')[j]
163
+ assert p._print_Indexed(x) == 'x[j]'
164
+ A = IndexedBase('A')[i, j]
165
+ assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
166
+ B = IndexedBase('B')[i, j, k]
167
+ assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
168
+
169
+ assert p._not_c == set()
170
+
171
+ def test_glsl_code_list_tuple_Tuple():
172
+ assert glsl_code([1,2,3,4]) == 'vec4(1, 2, 3, 4)'
173
+ assert glsl_code([1,2,3],glsl_types=False) == 'float[3](1, 2, 3)'
174
+ assert glsl_code([1,2,3]) == glsl_code((1,2,3))
175
+ assert glsl_code([1,2,3]) == glsl_code(Tuple(1,2,3))
176
+
177
+ m = MatrixSymbol('A',3,4)
178
+ assert glsl_code([m[0],m[1]])
179
+
180
+ def test_glsl_code_loops_matrix_vector():
181
+ n, m = symbols('n m', integer=True)
182
+ A = IndexedBase('A')
183
+ x = IndexedBase('x')
184
+ y = IndexedBase('y')
185
+ i = Idx('i', m)
186
+ j = Idx('j', n)
187
+
188
+ s = (
189
+ 'for (int i=0; i<m; i++){\n'
190
+ ' y[i] = 0.0;\n'
191
+ '}\n'
192
+ 'for (int i=0; i<m; i++){\n'
193
+ ' for (int j=0; j<n; j++){\n'
194
+ ' y[i] = A[n*i + j]*x[j] + y[i];\n'
195
+ ' }\n'
196
+ '}'
197
+ )
198
+
199
+ c = glsl_code(A[i, j]*x[j], assign_to=y[i])
200
+ assert c == s
201
+
202
+
203
+ def test_dummy_loops():
204
+ i, m = symbols('i m', integer=True, cls=Dummy)
205
+ x = IndexedBase('x')
206
+ y = IndexedBase('y')
207
+ i = Idx(i, m)
208
+
209
+ expected = (
210
+ 'for (int i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n'
211
+ ' y[i_%(icount)i] = x[i_%(icount)i];\n'
212
+ '}'
213
+ ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
214
+ code = glsl_code(x[i], assign_to=y[i])
215
+ assert code == expected
216
+
217
+
218
+ def test_glsl_code_loops_add():
219
+ n, m = symbols('n m', integer=True)
220
+ A = IndexedBase('A')
221
+ x = IndexedBase('x')
222
+ y = IndexedBase('y')
223
+ z = IndexedBase('z')
224
+ i = Idx('i', m)
225
+ j = Idx('j', n)
226
+
227
+ s = (
228
+ 'for (int i=0; i<m; i++){\n'
229
+ ' y[i] = x[i] + z[i];\n'
230
+ '}\n'
231
+ 'for (int i=0; i<m; i++){\n'
232
+ ' for (int j=0; j<n; j++){\n'
233
+ ' y[i] = A[n*i + j]*x[j] + y[i];\n'
234
+ ' }\n'
235
+ '}'
236
+ )
237
+ c = glsl_code(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i])
238
+ assert c == s
239
+
240
+
241
+ def test_glsl_code_loops_multiple_contractions():
242
+ n, m, o, p = symbols('n m o p', integer=True)
243
+ a = IndexedBase('a')
244
+ b = IndexedBase('b')
245
+ y = IndexedBase('y')
246
+ i = Idx('i', m)
247
+ j = Idx('j', n)
248
+ k = Idx('k', o)
249
+ l = Idx('l', p)
250
+
251
+ s = (
252
+ 'for (int i=0; i<m; i++){\n'
253
+ ' y[i] = 0.0;\n'
254
+ '}\n'
255
+ 'for (int i=0; i<m; i++){\n'
256
+ ' for (int j=0; j<n; j++){\n'
257
+ ' for (int k=0; k<o; k++){\n'
258
+ ' for (int l=0; l<p; l++){\n'
259
+ ' y[i] = a[%s]*b[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
260
+ ' }\n'
261
+ ' }\n'
262
+ ' }\n'
263
+ '}'
264
+ )
265
+ c = glsl_code(b[j, k, l]*a[i, j, k, l], assign_to=y[i])
266
+ assert c == s
267
+
268
+
269
+ def test_glsl_code_loops_addfactor():
270
+ n, m, o, p = symbols('n m o p', integer=True)
271
+ a = IndexedBase('a')
272
+ b = IndexedBase('b')
273
+ c = IndexedBase('c')
274
+ y = IndexedBase('y')
275
+ i = Idx('i', m)
276
+ j = Idx('j', n)
277
+ k = Idx('k', o)
278
+ l = Idx('l', p)
279
+
280
+ s = (
281
+ 'for (int i=0; i<m; i++){\n'
282
+ ' y[i] = 0.0;\n'
283
+ '}\n'
284
+ 'for (int i=0; i<m; i++){\n'
285
+ ' for (int j=0; j<n; j++){\n'
286
+ ' for (int k=0; k<o; k++){\n'
287
+ ' for (int l=0; l<p; l++){\n'
288
+ ' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
289
+ ' }\n'
290
+ ' }\n'
291
+ ' }\n'
292
+ '}'
293
+ )
294
+ c = glsl_code((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i])
295
+ assert c == s
296
+
297
+
298
+ def test_glsl_code_loops_multiple_terms():
299
+ n, m, o, p = symbols('n m o p', integer=True)
300
+ a = IndexedBase('a')
301
+ b = IndexedBase('b')
302
+ c = IndexedBase('c')
303
+ y = IndexedBase('y')
304
+ i = Idx('i', m)
305
+ j = Idx('j', n)
306
+ k = Idx('k', o)
307
+
308
+ s0 = (
309
+ 'for (int i=0; i<m; i++){\n'
310
+ ' y[i] = 0.0;\n'
311
+ '}\n'
312
+ )
313
+ s1 = (
314
+ 'for (int i=0; i<m; i++){\n'
315
+ ' for (int j=0; j<n; j++){\n'
316
+ ' for (int k=0; k<o; k++){\n'
317
+ ' y[i] = b[j]*b[k]*c[%s] + y[i];\n' % (i*n*o + j*o + k) +\
318
+ ' }\n'
319
+ ' }\n'
320
+ '}\n'
321
+ )
322
+ s2 = (
323
+ 'for (int i=0; i<m; i++){\n'
324
+ ' for (int k=0; k<o; k++){\n'
325
+ ' y[i] = a[%s]*b[k] + y[i];\n' % (i*o + k) +\
326
+ ' }\n'
327
+ '}\n'
328
+ )
329
+ s3 = (
330
+ 'for (int i=0; i<m; i++){\n'
331
+ ' for (int j=0; j<n; j++){\n'
332
+ ' y[i] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\
333
+ ' }\n'
334
+ '}\n'
335
+ )
336
+ c = glsl_code(
337
+ b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i])
338
+ assert (c == s0 + s1 + s2 + s3[:-1] or
339
+ c == s0 + s1 + s3 + s2[:-1] or
340
+ c == s0 + s2 + s1 + s3[:-1] or
341
+ c == s0 + s2 + s3 + s1[:-1] or
342
+ c == s0 + s3 + s1 + s2[:-1] or
343
+ c == s0 + s3 + s2 + s1[:-1])
344
+
345
+
346
+ def test_Matrix_printing():
347
+ # Test returning a Matrix
348
+
349
+ mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
350
+ A = MatrixSymbol('A', 3, 1)
351
+ assert glsl_code(mat, assign_to=A) == (
352
+ '''A[0][0] = x*y;
353
+ if (y > 0) {
354
+ A[1][0] = x + 2;
355
+ }
356
+ else {
357
+ A[1][0] = y;
358
+ }
359
+ A[2][0] = sin(z);''' )
360
+ assert glsl_code(Matrix([A[0],A[1]]))
361
+ # Test using MatrixElements in expressions
362
+ expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
363
+ assert glsl_code(expr) == (
364
+ '''((x > 0) ? (
365
+ 2*A[2][0]
366
+ )
367
+ : (
368
+ A[2][0]
369
+ )) + sin(A[1][0]) + A[0][0]''' )
370
+
371
+ # Test using MatrixElements in a Matrix
372
+ q = MatrixSymbol('q', 5, 1)
373
+ M = MatrixSymbol('M', 3, 3)
374
+ m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
375
+ [q[1,0] + q[2,0], q[3, 0], 5],
376
+ [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
377
+ assert glsl_code(m,M) == (
378
+ '''M[0][0] = sin(q[1]);
379
+ M[0][1] = 0;
380
+ M[0][2] = cos(q[2]);
381
+ M[1][0] = q[1] + q[2];
382
+ M[1][1] = q[3];
383
+ M[1][2] = 5;
384
+ M[2][0] = 2*q[4]/q[1];
385
+ M[2][1] = sqrt(q[0]) + 4;
386
+ M[2][2] = 0;'''
387
+ )
388
+
389
+ def test_Matrices_1x7():
390
+ gl = glsl_code
391
+ A = Matrix([1,2,3,4,5,6,7])
392
+ assert gl(A) == 'float[7](1, 2, 3, 4, 5, 6, 7)'
393
+ assert gl(A.transpose()) == 'float[7](1, 2, 3, 4, 5, 6, 7)'
394
+
395
+ def test_Matrices_1x7_array_type_int():
396
+ gl = glsl_code
397
+ A = Matrix([1,2,3,4,5,6,7])
398
+ assert gl(A, array_type='int') == 'int[7](1, 2, 3, 4, 5, 6, 7)'
399
+
400
+ def test_Tuple_array_type_custom():
401
+ gl = glsl_code
402
+ A = symbols('a b c')
403
+ assert gl(A, array_type='AbcType', glsl_types=False) == 'AbcType[3](a, b, c)'
404
+
405
+ def test_Matrices_1x7_spread_assign_to_symbols():
406
+ gl = glsl_code
407
+ A = Matrix([1,2,3,4,5,6,7])
408
+ assign_to = symbols('x.a x.b x.c x.d x.e x.f x.g')
409
+ assert gl(A, assign_to=assign_to) == textwrap.dedent('''\
410
+ x.a = 1;
411
+ x.b = 2;
412
+ x.c = 3;
413
+ x.d = 4;
414
+ x.e = 5;
415
+ x.f = 6;
416
+ x.g = 7;'''
417
+ )
418
+
419
+ def test_spread_assign_to_nested_symbols():
420
+ gl = glsl_code
421
+ expr = ((1,2,3), (1,2,3))
422
+ assign_to = (symbols('a b c'), symbols('x y z'))
423
+ assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\
424
+ a = 1;
425
+ b = 2;
426
+ c = 3;
427
+ x = 1;
428
+ y = 2;
429
+ z = 3;'''
430
+ )
431
+
432
+ def test_spread_assign_to_deeply_nested_symbols():
433
+ gl = glsl_code
434
+ a, b, c, x, y, z = symbols('a b c x y z')
435
+ expr = (((1,2),3), ((1,2),3))
436
+ assign_to = (((a, b), c), ((x, y), z))
437
+ assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\
438
+ a = 1;
439
+ b = 2;
440
+ c = 3;
441
+ x = 1;
442
+ y = 2;
443
+ z = 3;'''
444
+ )
445
+
446
+ def test_matrix_of_tuples_spread_assign_to_symbols():
447
+ gl = glsl_code
448
+ with warns_deprecated_sympy():
449
+ expr = Matrix([[(1,2),(3,4)],[(5,6),(7,8)]])
450
+ assign_to = (symbols('a b'), symbols('c d'), symbols('e f'), symbols('g h'))
451
+ assert gl(expr, assign_to) == textwrap.dedent('''\
452
+ a = 1;
453
+ b = 2;
454
+ c = 3;
455
+ d = 4;
456
+ e = 5;
457
+ f = 6;
458
+ g = 7;
459
+ h = 8;'''
460
+ )
461
+
462
+ def test_cannot_assign_to_cause_mismatched_length():
463
+ expr = (1, 2)
464
+ assign_to = symbols('x y z')
465
+ raises(ValueError, lambda: glsl_code(expr, assign_to))
466
+
467
+ def test_matrix_4x4_assign():
468
+ gl = glsl_code
469
+ expr = MatrixSymbol('A',4,4) * MatrixSymbol('B',4,4) + MatrixSymbol('C',4,4)
470
+ assign_to = MatrixSymbol('X',4,4)
471
+ assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\
472
+ X[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0] + A[0][2]*B[2][0] + A[0][3]*B[3][0] + C[0][0];
473
+ X[0][1] = A[0][0]*B[0][1] + A[0][1]*B[1][1] + A[0][2]*B[2][1] + A[0][3]*B[3][1] + C[0][1];
474
+ X[0][2] = A[0][0]*B[0][2] + A[0][1]*B[1][2] + A[0][2]*B[2][2] + A[0][3]*B[3][2] + C[0][2];
475
+ X[0][3] = A[0][0]*B[0][3] + A[0][1]*B[1][3] + A[0][2]*B[2][3] + A[0][3]*B[3][3] + C[0][3];
476
+ X[1][0] = A[1][0]*B[0][0] + A[1][1]*B[1][0] + A[1][2]*B[2][0] + A[1][3]*B[3][0] + C[1][0];
477
+ X[1][1] = A[1][0]*B[0][1] + A[1][1]*B[1][1] + A[1][2]*B[2][1] + A[1][3]*B[3][1] + C[1][1];
478
+ X[1][2] = A[1][0]*B[0][2] + A[1][1]*B[1][2] + A[1][2]*B[2][2] + A[1][3]*B[3][2] + C[1][2];
479
+ X[1][3] = A[1][0]*B[0][3] + A[1][1]*B[1][3] + A[1][2]*B[2][3] + A[1][3]*B[3][3] + C[1][3];
480
+ X[2][0] = A[2][0]*B[0][0] + A[2][1]*B[1][0] + A[2][2]*B[2][0] + A[2][3]*B[3][0] + C[2][0];
481
+ X[2][1] = A[2][0]*B[0][1] + A[2][1]*B[1][1] + A[2][2]*B[2][1] + A[2][3]*B[3][1] + C[2][1];
482
+ X[2][2] = A[2][0]*B[0][2] + A[2][1]*B[1][2] + A[2][2]*B[2][2] + A[2][3]*B[3][2] + C[2][2];
483
+ X[2][3] = A[2][0]*B[0][3] + A[2][1]*B[1][3] + A[2][2]*B[2][3] + A[2][3]*B[3][3] + C[2][3];
484
+ X[3][0] = A[3][0]*B[0][0] + A[3][1]*B[1][0] + A[3][2]*B[2][0] + A[3][3]*B[3][0] + C[3][0];
485
+ X[3][1] = A[3][0]*B[0][1] + A[3][1]*B[1][1] + A[3][2]*B[2][1] + A[3][3]*B[3][1] + C[3][1];
486
+ X[3][2] = A[3][0]*B[0][2] + A[3][1]*B[1][2] + A[3][2]*B[2][2] + A[3][3]*B[3][2] + C[3][2];
487
+ X[3][3] = A[3][0]*B[0][3] + A[3][1]*B[1][3] + A[3][2]*B[2][3] + A[3][3]*B[3][3] + C[3][3];'''
488
+ )
489
+
490
+ def test_1xN_vecs():
491
+ gl = glsl_code
492
+ for i in range(1,10):
493
+ A = Matrix(range(i))
494
+ assert gl(A.transpose()) == gl(A)
495
+ assert gl(A,mat_transpose=True) == gl(A)
496
+ if i > 1:
497
+ if i <= 4:
498
+ assert gl(A) == 'vec%s(%s)' % (i,', '.join(str(s) for s in range(i)))
499
+ else:
500
+ assert gl(A) == 'float[%s](%s)' % (i,', '.join(str(s) for s in range(i)))
501
+
502
+ def test_MxN_mats():
503
+ generatedAssertions='def test_misc_mats():\n'
504
+ for i in range(1,6):
505
+ for j in range(1,6):
506
+ A = Matrix([[x + y*j for x in range(j)] for y in range(i)])
507
+ gl = glsl_code(A)
508
+ glTransposed = glsl_code(A,mat_transpose=True)
509
+ generatedAssertions+=' mat = '+StrPrinter()._print(A)+'\n\n'
510
+ generatedAssertions+=' gl = \'\'\''+gl+'\'\'\'\n'
511
+ generatedAssertions+=' glTransposed = \'\'\''+glTransposed+'\'\'\'\n\n'
512
+ generatedAssertions+=' assert glsl_code(mat) == gl\n'
513
+ generatedAssertions+=' assert glsl_code(mat,mat_transpose=True) == glTransposed\n'
514
+ if i == 1 and j == 1:
515
+ assert gl == '0'
516
+ elif i <= 4 and j <= 4 and i>1 and j>1:
517
+ assert gl.startswith('mat%s' % j)
518
+ assert glTransposed.startswith('mat%s' % i)
519
+ elif i == 1 and j <= 4:
520
+ assert gl.startswith('vec')
521
+ elif j == 1 and i <= 4:
522
+ assert gl.startswith('vec')
523
+ elif i == 1:
524
+ assert gl.startswith('float[%s]('% j*i)
525
+ assert glTransposed.startswith('float[%s]('% j*i)
526
+ elif j == 1:
527
+ assert gl.startswith('float[%s]('% i*j)
528
+ assert glTransposed.startswith('float[%s]('% i*j)
529
+ else:
530
+ assert gl.startswith('float[%s](' % (i*j))
531
+ assert glTransposed.startswith('float[%s](' % (i*j))
532
+ glNested = glsl_code(A,mat_nested=True)
533
+ glNestedTransposed = glsl_code(A,mat_transpose=True,mat_nested=True)
534
+ assert glNested.startswith('float[%s][%s]' % (i,j))
535
+ assert glNestedTransposed.startswith('float[%s][%s]' % (j,i))
536
+ generatedAssertions+=' glNested = \'\'\''+glNested+'\'\'\'\n'
537
+ generatedAssertions+=' glNestedTransposed = \'\'\''+glNestedTransposed+'\'\'\'\n\n'
538
+ generatedAssertions+=' assert glsl_code(mat,mat_nested=True) == glNested\n'
539
+ generatedAssertions+=' assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed\n\n'
540
+ generateAssertions = False # set this to true to write bake these generated tests to a file
541
+ if generateAssertions:
542
+ gen = open('test_glsl_generated_matrices.py','w')
543
+ gen.write(generatedAssertions)
544
+ gen.close()
545
+
546
+
547
+ # these assertions were generated from the previous function
548
+ # glsl has complicated rules and this makes it easier to look over all the cases
549
+ def test_misc_mats():
550
+
551
+ mat = Matrix([[0]])
552
+
553
+ gl = '''0'''
554
+ glTransposed = '''0'''
555
+
556
+ assert glsl_code(mat) == gl
557
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
558
+
559
+ mat = Matrix([[0, 1]])
560
+
561
+ gl = '''vec2(0, 1)'''
562
+ glTransposed = '''vec2(0, 1)'''
563
+
564
+ assert glsl_code(mat) == gl
565
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
566
+
567
+ mat = Matrix([[0, 1, 2]])
568
+
569
+ gl = '''vec3(0, 1, 2)'''
570
+ glTransposed = '''vec3(0, 1, 2)'''
571
+
572
+ assert glsl_code(mat) == gl
573
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
574
+
575
+ mat = Matrix([[0, 1, 2, 3]])
576
+
577
+ gl = '''vec4(0, 1, 2, 3)'''
578
+ glTransposed = '''vec4(0, 1, 2, 3)'''
579
+
580
+ assert glsl_code(mat) == gl
581
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
582
+
583
+ mat = Matrix([[0, 1, 2, 3, 4]])
584
+
585
+ gl = '''float[5](0, 1, 2, 3, 4)'''
586
+ glTransposed = '''float[5](0, 1, 2, 3, 4)'''
587
+
588
+ assert glsl_code(mat) == gl
589
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
590
+
591
+ mat = Matrix([
592
+ [0],
593
+ [1]])
594
+
595
+ gl = '''vec2(0, 1)'''
596
+ glTransposed = '''vec2(0, 1)'''
597
+
598
+ assert glsl_code(mat) == gl
599
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
600
+
601
+ mat = Matrix([
602
+ [0, 1],
603
+ [2, 3]])
604
+
605
+ gl = '''mat2(0, 1, 2, 3)'''
606
+ glTransposed = '''mat2(0, 2, 1, 3)'''
607
+
608
+ assert glsl_code(mat) == gl
609
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
610
+
611
+ mat = Matrix([
612
+ [0, 1, 2],
613
+ [3, 4, 5]])
614
+
615
+ gl = '''mat3x2(0, 1, 2, 3, 4, 5)'''
616
+ glTransposed = '''mat2x3(0, 3, 1, 4, 2, 5)'''
617
+
618
+ assert glsl_code(mat) == gl
619
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
620
+
621
+ mat = Matrix([
622
+ [0, 1, 2, 3],
623
+ [4, 5, 6, 7]])
624
+
625
+ gl = '''mat4x2(0, 1, 2, 3, 4, 5, 6, 7)'''
626
+ glTransposed = '''mat2x4(0, 4, 1, 5, 2, 6, 3, 7)'''
627
+
628
+ assert glsl_code(mat) == gl
629
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
630
+
631
+ mat = Matrix([
632
+ [0, 1, 2, 3, 4],
633
+ [5, 6, 7, 8, 9]])
634
+
635
+ gl = '''float[10](
636
+ 0, 1, 2, 3, 4,
637
+ 5, 6, 7, 8, 9
638
+ ) /* a 2x5 matrix */'''
639
+ glTransposed = '''float[10](
640
+ 0, 5,
641
+ 1, 6,
642
+ 2, 7,
643
+ 3, 8,
644
+ 4, 9
645
+ ) /* a 5x2 matrix */'''
646
+
647
+ assert glsl_code(mat) == gl
648
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
649
+ glNested = '''float[2][5](
650
+ float[](0, 1, 2, 3, 4),
651
+ float[](5, 6, 7, 8, 9)
652
+ )'''
653
+ glNestedTransposed = '''float[5][2](
654
+ float[](0, 5),
655
+ float[](1, 6),
656
+ float[](2, 7),
657
+ float[](3, 8),
658
+ float[](4, 9)
659
+ )'''
660
+
661
+ assert glsl_code(mat,mat_nested=True) == glNested
662
+ assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
663
+
664
+ mat = Matrix([
665
+ [0],
666
+ [1],
667
+ [2]])
668
+
669
+ gl = '''vec3(0, 1, 2)'''
670
+ glTransposed = '''vec3(0, 1, 2)'''
671
+
672
+ assert glsl_code(mat) == gl
673
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
674
+
675
+ mat = Matrix([
676
+ [0, 1],
677
+ [2, 3],
678
+ [4, 5]])
679
+
680
+ gl = '''mat2x3(0, 1, 2, 3, 4, 5)'''
681
+ glTransposed = '''mat3x2(0, 2, 4, 1, 3, 5)'''
682
+
683
+ assert glsl_code(mat) == gl
684
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
685
+
686
+ mat = Matrix([
687
+ [0, 1, 2],
688
+ [3, 4, 5],
689
+ [6, 7, 8]])
690
+
691
+ gl = '''mat3(0, 1, 2, 3, 4, 5, 6, 7, 8)'''
692
+ glTransposed = '''mat3(0, 3, 6, 1, 4, 7, 2, 5, 8)'''
693
+
694
+ assert glsl_code(mat) == gl
695
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
696
+
697
+ mat = Matrix([
698
+ [0, 1, 2, 3],
699
+ [4, 5, 6, 7],
700
+ [8, 9, 10, 11]])
701
+
702
+ gl = '''mat4x3(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)'''
703
+ glTransposed = '''mat3x4(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11)'''
704
+
705
+ assert glsl_code(mat) == gl
706
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
707
+
708
+ mat = Matrix([
709
+ [ 0, 1, 2, 3, 4],
710
+ [ 5, 6, 7, 8, 9],
711
+ [10, 11, 12, 13, 14]])
712
+
713
+ gl = '''float[15](
714
+ 0, 1, 2, 3, 4,
715
+ 5, 6, 7, 8, 9,
716
+ 10, 11, 12, 13, 14
717
+ ) /* a 3x5 matrix */'''
718
+ glTransposed = '''float[15](
719
+ 0, 5, 10,
720
+ 1, 6, 11,
721
+ 2, 7, 12,
722
+ 3, 8, 13,
723
+ 4, 9, 14
724
+ ) /* a 5x3 matrix */'''
725
+
726
+ assert glsl_code(mat) == gl
727
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
728
+ glNested = '''float[3][5](
729
+ float[]( 0, 1, 2, 3, 4),
730
+ float[]( 5, 6, 7, 8, 9),
731
+ float[](10, 11, 12, 13, 14)
732
+ )'''
733
+ glNestedTransposed = '''float[5][3](
734
+ float[](0, 5, 10),
735
+ float[](1, 6, 11),
736
+ float[](2, 7, 12),
737
+ float[](3, 8, 13),
738
+ float[](4, 9, 14)
739
+ )'''
740
+
741
+ assert glsl_code(mat,mat_nested=True) == glNested
742
+ assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
743
+
744
+ mat = Matrix([
745
+ [0],
746
+ [1],
747
+ [2],
748
+ [3]])
749
+
750
+ gl = '''vec4(0, 1, 2, 3)'''
751
+ glTransposed = '''vec4(0, 1, 2, 3)'''
752
+
753
+ assert glsl_code(mat) == gl
754
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
755
+
756
+ mat = Matrix([
757
+ [0, 1],
758
+ [2, 3],
759
+ [4, 5],
760
+ [6, 7]])
761
+
762
+ gl = '''mat2x4(0, 1, 2, 3, 4, 5, 6, 7)'''
763
+ glTransposed = '''mat4x2(0, 2, 4, 6, 1, 3, 5, 7)'''
764
+
765
+ assert glsl_code(mat) == gl
766
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
767
+
768
+ mat = Matrix([
769
+ [0, 1, 2],
770
+ [3, 4, 5],
771
+ [6, 7, 8],
772
+ [9, 10, 11]])
773
+
774
+ gl = '''mat3x4(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)'''
775
+ glTransposed = '''mat4x3(0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11)'''
776
+
777
+ assert glsl_code(mat) == gl
778
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
779
+
780
+ mat = Matrix([
781
+ [ 0, 1, 2, 3],
782
+ [ 4, 5, 6, 7],
783
+ [ 8, 9, 10, 11],
784
+ [12, 13, 14, 15]])
785
+
786
+ gl = '''mat4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)'''
787
+ glTransposed = '''mat4(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15)'''
788
+
789
+ assert glsl_code(mat) == gl
790
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
791
+
792
+ mat = Matrix([
793
+ [ 0, 1, 2, 3, 4],
794
+ [ 5, 6, 7, 8, 9],
795
+ [10, 11, 12, 13, 14],
796
+ [15, 16, 17, 18, 19]])
797
+
798
+ gl = '''float[20](
799
+ 0, 1, 2, 3, 4,
800
+ 5, 6, 7, 8, 9,
801
+ 10, 11, 12, 13, 14,
802
+ 15, 16, 17, 18, 19
803
+ ) /* a 4x5 matrix */'''
804
+ glTransposed = '''float[20](
805
+ 0, 5, 10, 15,
806
+ 1, 6, 11, 16,
807
+ 2, 7, 12, 17,
808
+ 3, 8, 13, 18,
809
+ 4, 9, 14, 19
810
+ ) /* a 5x4 matrix */'''
811
+
812
+ assert glsl_code(mat) == gl
813
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
814
+ glNested = '''float[4][5](
815
+ float[]( 0, 1, 2, 3, 4),
816
+ float[]( 5, 6, 7, 8, 9),
817
+ float[](10, 11, 12, 13, 14),
818
+ float[](15, 16, 17, 18, 19)
819
+ )'''
820
+ glNestedTransposed = '''float[5][4](
821
+ float[](0, 5, 10, 15),
822
+ float[](1, 6, 11, 16),
823
+ float[](2, 7, 12, 17),
824
+ float[](3, 8, 13, 18),
825
+ float[](4, 9, 14, 19)
826
+ )'''
827
+
828
+ assert glsl_code(mat,mat_nested=True) == glNested
829
+ assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
830
+
831
+ mat = Matrix([
832
+ [0],
833
+ [1],
834
+ [2],
835
+ [3],
836
+ [4]])
837
+
838
+ gl = '''float[5](0, 1, 2, 3, 4)'''
839
+ glTransposed = '''float[5](0, 1, 2, 3, 4)'''
840
+
841
+ assert glsl_code(mat) == gl
842
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
843
+
844
+ mat = Matrix([
845
+ [0, 1],
846
+ [2, 3],
847
+ [4, 5],
848
+ [6, 7],
849
+ [8, 9]])
850
+
851
+ gl = '''float[10](
852
+ 0, 1,
853
+ 2, 3,
854
+ 4, 5,
855
+ 6, 7,
856
+ 8, 9
857
+ ) /* a 5x2 matrix */'''
858
+ glTransposed = '''float[10](
859
+ 0, 2, 4, 6, 8,
860
+ 1, 3, 5, 7, 9
861
+ ) /* a 2x5 matrix */'''
862
+
863
+ assert glsl_code(mat) == gl
864
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
865
+ glNested = '''float[5][2](
866
+ float[](0, 1),
867
+ float[](2, 3),
868
+ float[](4, 5),
869
+ float[](6, 7),
870
+ float[](8, 9)
871
+ )'''
872
+ glNestedTransposed = '''float[2][5](
873
+ float[](0, 2, 4, 6, 8),
874
+ float[](1, 3, 5, 7, 9)
875
+ )'''
876
+
877
+ assert glsl_code(mat,mat_nested=True) == glNested
878
+ assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
879
+
880
+ mat = Matrix([
881
+ [ 0, 1, 2],
882
+ [ 3, 4, 5],
883
+ [ 6, 7, 8],
884
+ [ 9, 10, 11],
885
+ [12, 13, 14]])
886
+
887
+ gl = '''float[15](
888
+ 0, 1, 2,
889
+ 3, 4, 5,
890
+ 6, 7, 8,
891
+ 9, 10, 11,
892
+ 12, 13, 14
893
+ ) /* a 5x3 matrix */'''
894
+ glTransposed = '''float[15](
895
+ 0, 3, 6, 9, 12,
896
+ 1, 4, 7, 10, 13,
897
+ 2, 5, 8, 11, 14
898
+ ) /* a 3x5 matrix */'''
899
+
900
+ assert glsl_code(mat) == gl
901
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
902
+ glNested = '''float[5][3](
903
+ float[]( 0, 1, 2),
904
+ float[]( 3, 4, 5),
905
+ float[]( 6, 7, 8),
906
+ float[]( 9, 10, 11),
907
+ float[](12, 13, 14)
908
+ )'''
909
+ glNestedTransposed = '''float[3][5](
910
+ float[](0, 3, 6, 9, 12),
911
+ float[](1, 4, 7, 10, 13),
912
+ float[](2, 5, 8, 11, 14)
913
+ )'''
914
+
915
+ assert glsl_code(mat,mat_nested=True) == glNested
916
+ assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
917
+
918
+ mat = Matrix([
919
+ [ 0, 1, 2, 3],
920
+ [ 4, 5, 6, 7],
921
+ [ 8, 9, 10, 11],
922
+ [12, 13, 14, 15],
923
+ [16, 17, 18, 19]])
924
+
925
+ gl = '''float[20](
926
+ 0, 1, 2, 3,
927
+ 4, 5, 6, 7,
928
+ 8, 9, 10, 11,
929
+ 12, 13, 14, 15,
930
+ 16, 17, 18, 19
931
+ ) /* a 5x4 matrix */'''
932
+ glTransposed = '''float[20](
933
+ 0, 4, 8, 12, 16,
934
+ 1, 5, 9, 13, 17,
935
+ 2, 6, 10, 14, 18,
936
+ 3, 7, 11, 15, 19
937
+ ) /* a 4x5 matrix */'''
938
+
939
+ assert glsl_code(mat) == gl
940
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
941
+ glNested = '''float[5][4](
942
+ float[]( 0, 1, 2, 3),
943
+ float[]( 4, 5, 6, 7),
944
+ float[]( 8, 9, 10, 11),
945
+ float[](12, 13, 14, 15),
946
+ float[](16, 17, 18, 19)
947
+ )'''
948
+ glNestedTransposed = '''float[4][5](
949
+ float[](0, 4, 8, 12, 16),
950
+ float[](1, 5, 9, 13, 17),
951
+ float[](2, 6, 10, 14, 18),
952
+ float[](3, 7, 11, 15, 19)
953
+ )'''
954
+
955
+ assert glsl_code(mat,mat_nested=True) == glNested
956
+ assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
957
+
958
+ mat = Matrix([
959
+ [ 0, 1, 2, 3, 4],
960
+ [ 5, 6, 7, 8, 9],
961
+ [10, 11, 12, 13, 14],
962
+ [15, 16, 17, 18, 19],
963
+ [20, 21, 22, 23, 24]])
964
+
965
+ gl = '''float[25](
966
+ 0, 1, 2, 3, 4,
967
+ 5, 6, 7, 8, 9,
968
+ 10, 11, 12, 13, 14,
969
+ 15, 16, 17, 18, 19,
970
+ 20, 21, 22, 23, 24
971
+ ) /* a 5x5 matrix */'''
972
+ glTransposed = '''float[25](
973
+ 0, 5, 10, 15, 20,
974
+ 1, 6, 11, 16, 21,
975
+ 2, 7, 12, 17, 22,
976
+ 3, 8, 13, 18, 23,
977
+ 4, 9, 14, 19, 24
978
+ ) /* a 5x5 matrix */'''
979
+
980
+ assert glsl_code(mat) == gl
981
+ assert glsl_code(mat,mat_transpose=True) == glTransposed
982
+ glNested = '''float[5][5](
983
+ float[]( 0, 1, 2, 3, 4),
984
+ float[]( 5, 6, 7, 8, 9),
985
+ float[](10, 11, 12, 13, 14),
986
+ float[](15, 16, 17, 18, 19),
987
+ float[](20, 21, 22, 23, 24)
988
+ )'''
989
+ glNestedTransposed = '''float[5][5](
990
+ float[](0, 5, 10, 15, 20),
991
+ float[](1, 6, 11, 16, 21),
992
+ float[](2, 7, 12, 17, 22),
993
+ float[](3, 8, 13, 18, 23),
994
+ float[](4, 9, 14, 19, 24)
995
+ )'''
996
+
997
+ assert glsl_code(mat,mat_nested=True) == glNested
998
+ assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_gtk.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.functions.elementary.trigonometric import sin
2
+ from sympy.printing.gtk import print_gtk
3
+ from sympy.testing.pytest import XFAIL, raises
4
+
5
+ # this test fails if python-lxml isn't installed. We don't want to depend on
6
+ # anything with SymPy
7
+
8
+
9
+ @XFAIL
10
+ def test_1():
11
+ from sympy.abc import x
12
+ print_gtk(x**2, start_viewer=False)
13
+ print_gtk(x**2 + sin(x)/4, start_viewer=False)
14
+
15
+
16
+ def test_settings():
17
+ from sympy.abc import x
18
+ raises(TypeError, lambda: print_gtk(x, method="garbage"))
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_jax.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.mod import Mod
3
+ from sympy.core.relational import (Equality, Unequality)
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.functions.elementary.piecewise import Piecewise
6
+ from sympy.matrices.expressions.blockmatrix import BlockMatrix
7
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
8
+ from sympy.matrices.expressions.special import Identity
9
+ from sympy.utilities.lambdify import lambdify
10
+
11
+ from sympy.abc import x, i, j, a, b, c, d
12
+ from sympy.core import Pow
13
+ from sympy.codegen.matrix_nodes import MatrixSolve
14
+ from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
15
+ from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt
16
+ from sympy.tensor.array import Array
17
+ from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
18
+ PermuteDims, ArrayDiagonal
19
+ from sympy.printing.numpy import JaxPrinter, _jax_known_constants, _jax_known_functions
20
+ from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
21
+
22
+ from sympy.testing.pytest import skip, raises
23
+ from sympy.external import import_module
24
+
25
+ # Unlike NumPy which will aggressively promote operands to double precision,
26
+ # jax always uses single precision. Double precision in jax can be
27
+ # configured before the call to `import jax`, however this must be explicitly
28
+ # configured and is not fully supported. Thus, the tests here have been modified
29
+ # from the tests in test_numpy.py, only in the fact that they assert lambdify
30
+ # function accuracy to only single precision accuracy.
31
+ # https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
32
+
33
+ jax = import_module('jax')
34
+
35
+ if jax:
36
+ deafult_float_info = jax.numpy.finfo(jax.numpy.array([]).dtype)
37
+ JAX_DEFAULT_EPSILON = deafult_float_info.eps
38
+
39
+ def test_jax_piecewise_regression():
40
+ """
41
+ NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
42
+ breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+.
43
+ See gh-9747 and gh-9749 for details.
44
+ """
45
+ printer = JaxPrinter()
46
+ p = Piecewise((1, x < 0), (0, True))
47
+ assert printer.doprint(p) == \
48
+ 'jax.numpy.select([jax.numpy.less(x, 0),True], [1,0], default=jax.numpy.nan)'
49
+ assert printer.module_imports == {'jax.numpy': {'select', 'less', 'nan'}}
50
+
51
+
52
+ def test_jax_logaddexp():
53
+ lae = logaddexp(a, b)
54
+ assert JaxPrinter().doprint(lae) == 'jax.numpy.logaddexp(a, b)'
55
+ lae2 = logaddexp2(a, b)
56
+ assert JaxPrinter().doprint(lae2) == 'jax.numpy.logaddexp2(a, b)'
57
+
58
+
59
+ def test_jax_sum():
60
+ if not jax:
61
+ skip("JAX not installed")
62
+
63
+ s = Sum(x ** i, (i, a, b))
64
+ f = lambdify((a, b, x), s, 'jax')
65
+
66
+ a_, b_ = 0, 10
67
+ x_ = jax.numpy.linspace(-1, +1, 10)
68
+ assert jax.numpy.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1)))
69
+
70
+ s = Sum(i * x, (i, a, b))
71
+ f = lambdify((a, b, x), s, 'jax')
72
+
73
+ a_, b_ = 0, 10
74
+ x_ = jax.numpy.linspace(-1, +1, 10)
75
+ assert jax.numpy.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
76
+
77
+
78
+ def test_jax_multiple_sums():
79
+ if not jax:
80
+ skip("JAX not installed")
81
+
82
+ s = Sum((x + j) * i, (i, a, b), (j, c, d))
83
+ f = lambdify((a, b, c, d, x), s, 'jax')
84
+
85
+ a_, b_ = 0, 10
86
+ c_, d_ = 11, 21
87
+ x_ = jax.numpy.linspace(-1, +1, 10)
88
+ assert jax.numpy.allclose(f(a_, b_, c_, d_, x_),
89
+ sum((x_ + j_) * i_ for i_ in range(a_, b_ + 1) for j_ in range(c_, d_ + 1)))
90
+
91
+
92
+ def test_jax_codegen_einsum():
93
+ if not jax:
94
+ skip("JAX not installed")
95
+
96
+ M = MatrixSymbol("M", 2, 2)
97
+ N = MatrixSymbol("N", 2, 2)
98
+
99
+ cg = convert_matrix_to_array(M * N)
100
+ f = lambdify((M, N), cg, 'jax')
101
+
102
+ ma = jax.numpy.array([[1, 2], [3, 4]])
103
+ mb = jax.numpy.array([[1,-2], [-1, 3]])
104
+ assert (f(ma, mb) == jax.numpy.matmul(ma, mb)).all()
105
+
106
+
107
+ def test_jax_codegen_extra():
108
+ if not jax:
109
+ skip("JAX not installed")
110
+
111
+ M = MatrixSymbol("M", 2, 2)
112
+ N = MatrixSymbol("N", 2, 2)
113
+ P = MatrixSymbol("P", 2, 2)
114
+ Q = MatrixSymbol("Q", 2, 2)
115
+ ma = jax.numpy.array([[1, 2], [3, 4]])
116
+ mb = jax.numpy.array([[1,-2], [-1, 3]])
117
+ mc = jax.numpy.array([[2, 0], [1, 2]])
118
+ md = jax.numpy.array([[1,-1], [4, 7]])
119
+
120
+ cg = ArrayTensorProduct(M, N)
121
+ f = lambdify((M, N), cg, 'jax')
122
+ assert (f(ma, mb) == jax.numpy.einsum(ma, [0, 1], mb, [2, 3])).all()
123
+
124
+ cg = ArrayAdd(M, N)
125
+ f = lambdify((M, N), cg, 'jax')
126
+ assert (f(ma, mb) == ma+mb).all()
127
+
128
+ cg = ArrayAdd(M, N, P)
129
+ f = lambdify((M, N, P), cg, 'jax')
130
+ assert (f(ma, mb, mc) == ma+mb+mc).all()
131
+
132
+ cg = ArrayAdd(M, N, P, Q)
133
+ f = lambdify((M, N, P, Q), cg, 'jax')
134
+ assert (f(ma, mb, mc, md) == ma+mb+mc+md).all()
135
+
136
+ cg = PermuteDims(M, [1, 0])
137
+ f = lambdify((M,), cg, 'jax')
138
+ assert (f(ma) == ma.T).all()
139
+
140
+ cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
141
+ f = lambdify((M, N), cg, 'jax')
142
+ assert (f(ma, mb) == jax.numpy.transpose(jax.numpy.einsum(ma, [0, 1], mb, [2, 3]), (1, 2, 3, 0))).all()
143
+
144
+ cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
145
+ f = lambdify((M, N), cg, 'jax')
146
+ assert (f(ma, mb) == jax.numpy.diagonal(jax.numpy.einsum(ma, [0, 1], mb, [2, 3]), axis1=1, axis2=2)).all()
147
+
148
+
149
+ def test_jax_relational():
150
+ if not jax:
151
+ skip("JAX not installed")
152
+
153
+ e = Equality(x, 1)
154
+
155
+ f = lambdify((x,), e, 'jax')
156
+ x_ = jax.numpy.array([0, 1, 2])
157
+ assert jax.numpy.array_equal(f(x_), [False, True, False])
158
+
159
+ e = Unequality(x, 1)
160
+
161
+ f = lambdify((x,), e, 'jax')
162
+ x_ = jax.numpy.array([0, 1, 2])
163
+ assert jax.numpy.array_equal(f(x_), [True, False, True])
164
+
165
+ e = (x < 1)
166
+
167
+ f = lambdify((x,), e, 'jax')
168
+ x_ = jax.numpy.array([0, 1, 2])
169
+ assert jax.numpy.array_equal(f(x_), [True, False, False])
170
+
171
+ e = (x <= 1)
172
+
173
+ f = lambdify((x,), e, 'jax')
174
+ x_ = jax.numpy.array([0, 1, 2])
175
+ assert jax.numpy.array_equal(f(x_), [True, True, False])
176
+
177
+ e = (x > 1)
178
+
179
+ f = lambdify((x,), e, 'jax')
180
+ x_ = jax.numpy.array([0, 1, 2])
181
+ assert jax.numpy.array_equal(f(x_), [False, False, True])
182
+
183
+ e = (x >= 1)
184
+
185
+ f = lambdify((x,), e, 'jax')
186
+ x_ = jax.numpy.array([0, 1, 2])
187
+ assert jax.numpy.array_equal(f(x_), [False, True, True])
188
+
189
+ # Multi-condition expressions
190
+ e = (x >= 1) & (x < 2)
191
+ f = lambdify((x,), e, 'jax')
192
+ x_ = jax.numpy.array([0, 1, 2])
193
+ assert jax.numpy.array_equal(f(x_), [False, True, False])
194
+
195
+ e = (x >= 1) | (x < 2)
196
+ f = lambdify((x,), e, 'jax')
197
+ x_ = jax.numpy.array([0, 1, 2])
198
+ assert jax.numpy.array_equal(f(x_), [True, True, True])
199
+
200
+ def test_jax_mod():
201
+ if not jax:
202
+ skip("JAX not installed")
203
+
204
+ e = Mod(a, b)
205
+ f = lambdify((a, b), e, 'jax')
206
+
207
+ a_ = jax.numpy.array([0, 1, 2, 3])
208
+ b_ = 2
209
+ assert jax.numpy.array_equal(f(a_, b_), [0, 1, 0, 1])
210
+
211
+ a_ = jax.numpy.array([0, 1, 2, 3])
212
+ b_ = jax.numpy.array([2, 2, 2, 2])
213
+ assert jax.numpy.array_equal(f(a_, b_), [0, 1, 0, 1])
214
+
215
+ a_ = jax.numpy.array([2, 3, 4, 5])
216
+ b_ = jax.numpy.array([2, 3, 4, 5])
217
+ assert jax.numpy.array_equal(f(a_, b_), [0, 0, 0, 0])
218
+
219
+
220
+ def test_jax_pow():
221
+ if not jax:
222
+ skip('JAX not installed')
223
+
224
+ expr = Pow(2, -1, evaluate=False)
225
+ f = lambdify([], expr, 'jax')
226
+ assert f() == 0.5
227
+
228
+
229
+ def test_jax_expm1():
230
+ if not jax:
231
+ skip("JAX not installed")
232
+
233
+ f = lambdify((a,), expm1(a), 'jax')
234
+ assert abs(f(1e-10) - 1e-10 - 5e-21) <= 1e-10 * JAX_DEFAULT_EPSILON
235
+
236
+
237
+ def test_jax_log1p():
238
+ if not jax:
239
+ skip("JAX not installed")
240
+
241
+ f = lambdify((a,), log1p(a), 'jax')
242
+ assert abs(f(1e-99) - 1e-99) <= 1e-99 * JAX_DEFAULT_EPSILON
243
+
244
+ def test_jax_hypot():
245
+ if not jax:
246
+ skip("JAX not installed")
247
+ assert abs(lambdify((a, b), hypot(a, b), 'jax')(3, 4) - 5) <= JAX_DEFAULT_EPSILON
248
+
249
+ def test_jax_log10():
250
+ if not jax:
251
+ skip("JAX not installed")
252
+
253
+ assert abs(lambdify((a,), log10(a), 'jax')(100) - 2) <= JAX_DEFAULT_EPSILON
254
+
255
+
256
+ def test_jax_exp2():
257
+ if not jax:
258
+ skip("JAX not installed")
259
+ assert abs(lambdify((a,), exp2(a), 'jax')(5) - 32) <= JAX_DEFAULT_EPSILON
260
+
261
+
262
+ def test_jax_log2():
263
+ if not jax:
264
+ skip("JAX not installed")
265
+ assert abs(lambdify((a,), log2(a), 'jax')(256) - 8) <= JAX_DEFAULT_EPSILON
266
+
267
+
268
+ def test_jax_Sqrt():
269
+ if not jax:
270
+ skip("JAX not installed")
271
+ assert abs(lambdify((a,), Sqrt(a), 'jax')(4) - 2) <= JAX_DEFAULT_EPSILON
272
+
273
+
274
+ def test_jax_sqrt():
275
+ if not jax:
276
+ skip("JAX not installed")
277
+ assert abs(lambdify((a,), sqrt(a), 'jax')(4) - 2) <= JAX_DEFAULT_EPSILON
278
+
279
+
280
+ def test_jax_matsolve():
281
+ if not jax:
282
+ skip("JAX not installed")
283
+
284
+ M = MatrixSymbol("M", 3, 3)
285
+ x = MatrixSymbol("x", 3, 1)
286
+
287
+ expr = M**(-1) * x + x
288
+ matsolve_expr = MatrixSolve(M, x) + x
289
+
290
+ f = lambdify((M, x), expr, 'jax')
291
+ f_matsolve = lambdify((M, x), matsolve_expr, 'jax')
292
+
293
+ m0 = jax.numpy.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]])
294
+ assert jax.numpy.linalg.matrix_rank(m0) == 3
295
+
296
+ x0 = jax.numpy.array([3, 4, 5])
297
+
298
+ assert jax.numpy.allclose(f_matsolve(m0, x0), f(m0, x0))
299
+
300
+
301
+ def test_16857():
302
+ if not jax:
303
+ skip("JAX not installed")
304
+
305
+ a_1 = MatrixSymbol('a_1', 10, 3)
306
+ a_2 = MatrixSymbol('a_2', 10, 3)
307
+ a_3 = MatrixSymbol('a_3', 10, 3)
308
+ a_4 = MatrixSymbol('a_4', 10, 3)
309
+ A = BlockMatrix([[a_1, a_2], [a_3, a_4]])
310
+ assert A.shape == (20, 6)
311
+
312
+ printer = JaxPrinter()
313
+ assert printer.doprint(A) == 'jax.numpy.block([[a_1, a_2], [a_3, a_4]])'
314
+
315
+
316
+ def test_issue_17006():
317
+ if not jax:
318
+ skip("JAX not installed")
319
+
320
+ M = MatrixSymbol("M", 2, 2)
321
+
322
+ f = lambdify(M, M + Identity(2), 'jax')
323
+ ma = jax.numpy.array([[1, 2], [3, 4]])
324
+ mr = jax.numpy.array([[2, 2], [3, 5]])
325
+
326
+ assert (f(ma) == mr).all()
327
+
328
+ from sympy.core.symbol import symbols
329
+ n = symbols('n', integer=True)
330
+ N = MatrixSymbol("M", n, n)
331
+ raises(NotImplementedError, lambda: lambdify(N, N + Identity(n), 'jax'))
332
+
333
+ def test_jax_array():
334
+ assert JaxPrinter().doprint(Array(((1, 2), (3, 5)))) == 'jax.numpy.array([[1, 2], [3, 5]])'
335
+ assert JaxPrinter().doprint(Array((1, 2))) == 'jax.numpy.array((1, 2))'
336
+
337
+ def test_jax_known_funcs_consts():
338
+ assert _jax_known_constants['NaN'] == 'jax.numpy.nan'
339
+ assert _jax_known_constants['EulerGamma'] == 'jax.numpy.euler_gamma'
340
+
341
+ assert _jax_known_functions['acos'] == 'jax.numpy.arccos'
342
+ assert _jax_known_functions['log'] == 'jax.numpy.log'
343
+
344
+ def test_jax_print_methods():
345
+ prntr = JaxPrinter()
346
+ assert hasattr(prntr, '_print_acos')
347
+ assert hasattr(prntr, '_print_log')
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_jscode.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import (pi, oo, symbols, Rational, Integer, GoldenRatio,
2
+ EulerGamma, Catalan, Lambda, Dummy, S, Eq, Ne, Le,
3
+ Lt, Gt, Ge, Mod)
4
+ from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt,
5
+ sinh, cosh, tanh, asin, acos, acosh, Max, Min)
6
+ from sympy.testing.pytest import raises
7
+ from sympy.printing.jscode import JavascriptCodePrinter
8
+ from sympy.utilities.lambdify import implemented_function
9
+ from sympy.tensor import IndexedBase, Idx
10
+ from sympy.matrices import Matrix, MatrixSymbol
11
+
12
+ from sympy.printing.jscode import jscode
13
+
14
+ x, y, z = symbols('x,y,z')
15
+
16
+
17
+ def test_printmethod():
18
+ assert jscode(Abs(x)) == "Math.abs(x)"
19
+
20
+
21
+ def test_jscode_sqrt():
22
+ assert jscode(sqrt(x)) == "Math.sqrt(x)"
23
+ assert jscode(x**0.5) == "Math.sqrt(x)"
24
+ assert jscode(x**(S.One/3)) == "Math.cbrt(x)"
25
+
26
+
27
+ def test_jscode_Pow():
28
+ g = implemented_function('g', Lambda(x, 2*x))
29
+ assert jscode(x**3) == "Math.pow(x, 3)"
30
+ assert jscode(x**(y**3)) == "Math.pow(x, Math.pow(y, 3))"
31
+ assert jscode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
32
+ "Math.pow(3.5*2*x, -x + Math.pow(y, x))/(Math.pow(x, 2) + y)"
33
+ assert jscode(x**-1.0) == '1/x'
34
+
35
+
36
+ def test_jscode_constants_mathh():
37
+ assert jscode(exp(1)) == "Math.E"
38
+ assert jscode(pi) == "Math.PI"
39
+ assert jscode(oo) == "Number.POSITIVE_INFINITY"
40
+ assert jscode(-oo) == "Number.NEGATIVE_INFINITY"
41
+
42
+
43
+ def test_jscode_constants_other():
44
+ assert jscode(
45
+ 2*GoldenRatio) == "var GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17)
46
+ assert jscode(2*Catalan) == "var Catalan = %s;\n2*Catalan" % Catalan.evalf(17)
47
+ assert jscode(
48
+ 2*EulerGamma) == "var EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17)
49
+
50
+
51
+ def test_jscode_Rational():
52
+ assert jscode(Rational(3, 7)) == "3/7"
53
+ assert jscode(Rational(18, 9)) == "2"
54
+ assert jscode(Rational(3, -7)) == "-3/7"
55
+ assert jscode(Rational(-3, -7)) == "3/7"
56
+
57
+
58
+ def test_Relational():
59
+ assert jscode(Eq(x, y)) == "x == y"
60
+ assert jscode(Ne(x, y)) == "x != y"
61
+ assert jscode(Le(x, y)) == "x <= y"
62
+ assert jscode(Lt(x, y)) == "x < y"
63
+ assert jscode(Gt(x, y)) == "x > y"
64
+ assert jscode(Ge(x, y)) == "x >= y"
65
+
66
+
67
+ def test_Mod():
68
+ assert jscode(Mod(x, y)) == '((x % y) + y) % y'
69
+ assert jscode(Mod(x, x + y)) == '((x % (x + y)) + (x + y)) % (x + y)'
70
+ p1, p2 = symbols('p1 p2', positive=True)
71
+ assert jscode(Mod(p1, p2)) == 'p1 % p2'
72
+ assert jscode(Mod(p1, p2 + 3)) == 'p1 % (p2 + 3)'
73
+ assert jscode(Mod(-3, -7, evaluate=False)) == '(-3) % (-7)'
74
+ assert jscode(-Mod(p1, p2)) == '-(p1 % p2)'
75
+ assert jscode(x*Mod(p1, p2)) == 'x*(p1 % p2)'
76
+
77
+
78
+ def test_jscode_Integer():
79
+ assert jscode(Integer(67)) == "67"
80
+ assert jscode(Integer(-1)) == "-1"
81
+
82
+
83
+ def test_jscode_functions():
84
+ assert jscode(sin(x) ** cos(x)) == "Math.pow(Math.sin(x), Math.cos(x))"
85
+ assert jscode(sinh(x) * cosh(x)) == "Math.sinh(x)*Math.cosh(x)"
86
+ assert jscode(Max(x, y) + Min(x, y)) == "Math.max(x, y) + Math.min(x, y)"
87
+ assert jscode(tanh(x)*acosh(y)) == "Math.tanh(x)*Math.acosh(y)"
88
+ assert jscode(asin(x)-acos(y)) == "-Math.acos(y) + Math.asin(x)"
89
+
90
+
91
+ def test_jscode_inline_function():
92
+ x = symbols('x')
93
+ g = implemented_function('g', Lambda(x, 2*x))
94
+ assert jscode(g(x)) == "2*x"
95
+ g = implemented_function('g', Lambda(x, 2*x/Catalan))
96
+ assert jscode(g(x)) == "var Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17)
97
+ A = IndexedBase('A')
98
+ i = Idx('i', symbols('n', integer=True))
99
+ g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
100
+ assert jscode(g(A[i]), assign_to=A[i]) == (
101
+ "for (var i=0; i<n; i++){\n"
102
+ " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
103
+ "}"
104
+ )
105
+
106
+
107
+ def test_jscode_exceptions():
108
+ assert jscode(ceiling(x)) == "Math.ceil(x)"
109
+ assert jscode(Abs(x)) == "Math.abs(x)"
110
+
111
+
112
+ def test_jscode_boolean():
113
+ assert jscode(x & y) == "x && y"
114
+ assert jscode(x | y) == "x || y"
115
+ assert jscode(~x) == "!x"
116
+ assert jscode(x & y & z) == "x && y && z"
117
+ assert jscode(x | y | z) == "x || y || z"
118
+ assert jscode((x & y) | z) == "z || x && y"
119
+ assert jscode((x | y) & z) == "z && (x || y)"
120
+
121
+
122
+ def test_jscode_Piecewise():
123
+ expr = Piecewise((x, x < 1), (x**2, True))
124
+ p = jscode(expr)
125
+ s = \
126
+ """\
127
+ ((x < 1) ? (
128
+ x
129
+ )
130
+ : (
131
+ Math.pow(x, 2)
132
+ ))\
133
+ """
134
+ assert p == s
135
+ assert jscode(expr, assign_to="c") == (
136
+ "if (x < 1) {\n"
137
+ " c = x;\n"
138
+ "}\n"
139
+ "else {\n"
140
+ " c = Math.pow(x, 2);\n"
141
+ "}")
142
+ # Check that Piecewise without a True (default) condition error
143
+ expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
144
+ raises(ValueError, lambda: jscode(expr))
145
+
146
+
147
+ def test_jscode_Piecewise_deep():
148
+ p = jscode(2*Piecewise((x, x < 1), (x**2, True)))
149
+ s = \
150
+ """\
151
+ 2*((x < 1) ? (
152
+ x
153
+ )
154
+ : (
155
+ Math.pow(x, 2)
156
+ ))\
157
+ """
158
+ assert p == s
159
+
160
+
161
+ def test_jscode_settings():
162
+ raises(TypeError, lambda: jscode(sin(x), method="garbage"))
163
+
164
+
165
+ def test_jscode_Indexed():
166
+ n, m, o = symbols('n m o', integer=True)
167
+ i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
168
+ p = JavascriptCodePrinter()
169
+ p._not_c = set()
170
+
171
+ x = IndexedBase('x')[j]
172
+ assert p._print_Indexed(x) == 'x[j]'
173
+ A = IndexedBase('A')[i, j]
174
+ assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
175
+ B = IndexedBase('B')[i, j, k]
176
+ assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
177
+
178
+ assert p._not_c == set()
179
+
180
+
181
+ def test_jscode_loops_matrix_vector():
182
+ n, m = symbols('n m', integer=True)
183
+ A = IndexedBase('A')
184
+ x = IndexedBase('x')
185
+ y = IndexedBase('y')
186
+ i = Idx('i', m)
187
+ j = Idx('j', n)
188
+
189
+ s = (
190
+ 'for (var i=0; i<m; i++){\n'
191
+ ' y[i] = 0;\n'
192
+ '}\n'
193
+ 'for (var i=0; i<m; i++){\n'
194
+ ' for (var j=0; j<n; j++){\n'
195
+ ' y[i] = A[n*i + j]*x[j] + y[i];\n'
196
+ ' }\n'
197
+ '}'
198
+ )
199
+ c = jscode(A[i, j]*x[j], assign_to=y[i])
200
+ assert c == s
201
+
202
+
203
+ def test_dummy_loops():
204
+ i, m = symbols('i m', integer=True, cls=Dummy)
205
+ x = IndexedBase('x')
206
+ y = IndexedBase('y')
207
+ i = Idx(i, m)
208
+
209
+ expected = (
210
+ 'for (var i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n'
211
+ ' y[i_%(icount)i] = x[i_%(icount)i];\n'
212
+ '}'
213
+ ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
214
+ code = jscode(x[i], assign_to=y[i])
215
+ assert code == expected
216
+
217
+
218
+ def test_jscode_loops_add():
219
+ n, m = symbols('n m', integer=True)
220
+ A = IndexedBase('A')
221
+ x = IndexedBase('x')
222
+ y = IndexedBase('y')
223
+ z = IndexedBase('z')
224
+ i = Idx('i', m)
225
+ j = Idx('j', n)
226
+
227
+ s = (
228
+ 'for (var i=0; i<m; i++){\n'
229
+ ' y[i] = x[i] + z[i];\n'
230
+ '}\n'
231
+ 'for (var i=0; i<m; i++){\n'
232
+ ' for (var j=0; j<n; j++){\n'
233
+ ' y[i] = A[n*i + j]*x[j] + y[i];\n'
234
+ ' }\n'
235
+ '}'
236
+ )
237
+ c = jscode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i])
238
+ assert c == s
239
+
240
+
241
+ def test_jscode_loops_multiple_contractions():
242
+ n, m, o, p = symbols('n m o p', integer=True)
243
+ a = IndexedBase('a')
244
+ b = IndexedBase('b')
245
+ y = IndexedBase('y')
246
+ i = Idx('i', m)
247
+ j = Idx('j', n)
248
+ k = Idx('k', o)
249
+ l = Idx('l', p)
250
+
251
+ s = (
252
+ 'for (var i=0; i<m; i++){\n'
253
+ ' y[i] = 0;\n'
254
+ '}\n'
255
+ 'for (var i=0; i<m; i++){\n'
256
+ ' for (var j=0; j<n; j++){\n'
257
+ ' for (var k=0; k<o; k++){\n'
258
+ ' for (var l=0; l<p; l++){\n'
259
+ ' y[i] = a[%s]*b[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
260
+ ' }\n'
261
+ ' }\n'
262
+ ' }\n'
263
+ '}'
264
+ )
265
+ c = jscode(b[j, k, l]*a[i, j, k, l], assign_to=y[i])
266
+ assert c == s
267
+
268
+
269
+ def test_jscode_loops_addfactor():
270
+ n, m, o, p = symbols('n m o p', integer=True)
271
+ a = IndexedBase('a')
272
+ b = IndexedBase('b')
273
+ c = IndexedBase('c')
274
+ y = IndexedBase('y')
275
+ i = Idx('i', m)
276
+ j = Idx('j', n)
277
+ k = Idx('k', o)
278
+ l = Idx('l', p)
279
+
280
+ s = (
281
+ 'for (var i=0; i<m; i++){\n'
282
+ ' y[i] = 0;\n'
283
+ '}\n'
284
+ 'for (var i=0; i<m; i++){\n'
285
+ ' for (var j=0; j<n; j++){\n'
286
+ ' for (var k=0; k<o; k++){\n'
287
+ ' for (var l=0; l<p; l++){\n'
288
+ ' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
289
+ ' }\n'
290
+ ' }\n'
291
+ ' }\n'
292
+ '}'
293
+ )
294
+ c = jscode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i])
295
+ assert c == s
296
+
297
+
298
+ def test_jscode_loops_multiple_terms():
299
+ n, m, o, p = symbols('n m o p', integer=True)
300
+ a = IndexedBase('a')
301
+ b = IndexedBase('b')
302
+ c = IndexedBase('c')
303
+ y = IndexedBase('y')
304
+ i = Idx('i', m)
305
+ j = Idx('j', n)
306
+ k = Idx('k', o)
307
+
308
+ s0 = (
309
+ 'for (var i=0; i<m; i++){\n'
310
+ ' y[i] = 0;\n'
311
+ '}\n'
312
+ )
313
+ s1 = (
314
+ 'for (var i=0; i<m; i++){\n'
315
+ ' for (var j=0; j<n; j++){\n'
316
+ ' for (var k=0; k<o; k++){\n'
317
+ ' y[i] = b[j]*b[k]*c[%s] + y[i];\n' % (i*n*o + j*o + k) +\
318
+ ' }\n'
319
+ ' }\n'
320
+ '}\n'
321
+ )
322
+ s2 = (
323
+ 'for (var i=0; i<m; i++){\n'
324
+ ' for (var k=0; k<o; k++){\n'
325
+ ' y[i] = a[%s]*b[k] + y[i];\n' % (i*o + k) +\
326
+ ' }\n'
327
+ '}\n'
328
+ )
329
+ s3 = (
330
+ 'for (var i=0; i<m; i++){\n'
331
+ ' for (var j=0; j<n; j++){\n'
332
+ ' y[i] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\
333
+ ' }\n'
334
+ '}\n'
335
+ )
336
+ c = jscode(
337
+ b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i])
338
+ assert (c == s0 + s1 + s2 + s3[:-1] or
339
+ c == s0 + s1 + s3 + s2[:-1] or
340
+ c == s0 + s2 + s1 + s3[:-1] or
341
+ c == s0 + s2 + s3 + s1[:-1] or
342
+ c == s0 + s3 + s1 + s2[:-1] or
343
+ c == s0 + s3 + s2 + s1[:-1])
344
+
345
+
346
+ def test_Matrix_printing():
347
+ # Test returning a Matrix
348
+ mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
349
+ A = MatrixSymbol('A', 3, 1)
350
+ assert jscode(mat, A) == (
351
+ "A[0] = x*y;\n"
352
+ "if (y > 0) {\n"
353
+ " A[1] = x + 2;\n"
354
+ "}\n"
355
+ "else {\n"
356
+ " A[1] = y;\n"
357
+ "}\n"
358
+ "A[2] = Math.sin(z);")
359
+ # Test using MatrixElements in expressions
360
+ expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
361
+ assert jscode(expr) == (
362
+ "((x > 0) ? (\n"
363
+ " 2*A[2]\n"
364
+ ")\n"
365
+ ": (\n"
366
+ " A[2]\n"
367
+ ")) + Math.sin(A[1]) + A[0]")
368
+ # Test using MatrixElements in a Matrix
369
+ q = MatrixSymbol('q', 5, 1)
370
+ M = MatrixSymbol('M', 3, 3)
371
+ m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
372
+ [q[1,0] + q[2,0], q[3, 0], 5],
373
+ [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
374
+ assert jscode(m, M) == (
375
+ "M[0] = Math.sin(q[1]);\n"
376
+ "M[1] = 0;\n"
377
+ "M[2] = Math.cos(q[2]);\n"
378
+ "M[3] = q[1] + q[2];\n"
379
+ "M[4] = q[3];\n"
380
+ "M[5] = 5;\n"
381
+ "M[6] = 2*q[4]/q[1];\n"
382
+ "M[7] = Math.sqrt(q[0]) + 4;\n"
383
+ "M[8] = 0;")
384
+
385
+
386
+ def test_MatrixElement_printing():
387
+ # test cases for issue #11821
388
+ A = MatrixSymbol("A", 1, 3)
389
+ B = MatrixSymbol("B", 1, 3)
390
+ C = MatrixSymbol("C", 1, 3)
391
+
392
+ assert(jscode(A[0, 0]) == "A[0]")
393
+ assert(jscode(3 * A[0, 0]) == "3*A[0]")
394
+
395
+ F = C[0, 0].subs(C, A - B)
396
+ assert(jscode(F) == "(A - B)[0]")
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_julia.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer,
2
+ Tuple, Symbol, Eq, Ne, Le, Lt, Gt, Ge)
3
+ from sympy.core import EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow
4
+ from sympy.functions import Piecewise, sqrt, ceiling, exp, sin, cos
5
+ from sympy.testing.pytest import raises
6
+ from sympy.utilities.lambdify import implemented_function
7
+ from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity,
8
+ HadamardProduct, SparseMatrix)
9
+ from sympy.functions.special.bessel import (jn, yn, besselj, bessely, besseli,
10
+ besselk, hankel1, hankel2, airyai,
11
+ airybi, airyaiprime, airybiprime)
12
+ from sympy.testing.pytest import XFAIL
13
+
14
+ from sympy.printing.julia import julia_code
15
+
16
+ x, y, z = symbols('x,y,z')
17
+
18
+
19
+ def test_Integer():
20
+ assert julia_code(Integer(67)) == "67"
21
+ assert julia_code(Integer(-1)) == "-1"
22
+
23
+
24
+ def test_Rational():
25
+ assert julia_code(Rational(3, 7)) == "3 // 7"
26
+ assert julia_code(Rational(18, 9)) == "2"
27
+ assert julia_code(Rational(3, -7)) == "-3 // 7"
28
+ assert julia_code(Rational(-3, -7)) == "3 // 7"
29
+ assert julia_code(x + Rational(3, 7)) == "x + 3 // 7"
30
+ assert julia_code(Rational(3, 7)*x) == "(3 // 7) * x"
31
+
32
+
33
+ def test_Relational():
34
+ assert julia_code(Eq(x, y)) == "x == y"
35
+ assert julia_code(Ne(x, y)) == "x != y"
36
+ assert julia_code(Le(x, y)) == "x <= y"
37
+ assert julia_code(Lt(x, y)) == "x < y"
38
+ assert julia_code(Gt(x, y)) == "x > y"
39
+ assert julia_code(Ge(x, y)) == "x >= y"
40
+
41
+
42
+ def test_Function():
43
+ assert julia_code(sin(x) ** cos(x)) == "sin(x) .^ cos(x)"
44
+ assert julia_code(abs(x)) == "abs(x)"
45
+ assert julia_code(ceiling(x)) == "ceil(x)"
46
+
47
+
48
+ def test_Pow():
49
+ assert julia_code(x**3) == "x .^ 3"
50
+ assert julia_code(x**(y**3)) == "x .^ (y .^ 3)"
51
+ assert julia_code(x**Rational(2, 3)) == 'x .^ (2 // 3)'
52
+ g = implemented_function('g', Lambda(x, 2*x))
53
+ assert julia_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
54
+ "(3.5 * 2 * x) .^ (-x + y .^ x) ./ (x .^ 2 + y)"
55
+ # For issue 14160
56
+ assert julia_code(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
57
+ evaluate=False)) == '-2 * x ./ (y .* y)'
58
+
59
+
60
+ def test_basic_ops():
61
+ assert julia_code(x*y) == "x .* y"
62
+ assert julia_code(x + y) == "x + y"
63
+ assert julia_code(x - y) == "x - y"
64
+ assert julia_code(-x) == "-x"
65
+
66
+
67
+ def test_1_over_x_and_sqrt():
68
+ # 1.0 and 0.5 would do something different in regular StrPrinter,
69
+ # but these are exact in IEEE floating point so no different here.
70
+ assert julia_code(1/x) == '1 ./ x'
71
+ assert julia_code(x**-1) == julia_code(x**-1.0) == '1 ./ x'
72
+ assert julia_code(1/sqrt(x)) == '1 ./ sqrt(x)'
73
+ assert julia_code(x**-S.Half) == julia_code(x**-0.5) == '1 ./ sqrt(x)'
74
+ assert julia_code(sqrt(x)) == 'sqrt(x)'
75
+ assert julia_code(x**S.Half) == julia_code(x**0.5) == 'sqrt(x)'
76
+ assert julia_code(1/pi) == '1 / pi'
77
+ assert julia_code(pi**-1) == julia_code(pi**-1.0) == '1 / pi'
78
+ assert julia_code(pi**-0.5) == '1 / sqrt(pi)'
79
+
80
+
81
+ def test_mix_number_mult_symbols():
82
+ assert julia_code(3*x) == "3 * x"
83
+ assert julia_code(pi*x) == "pi * x"
84
+ assert julia_code(3/x) == "3 ./ x"
85
+ assert julia_code(pi/x) == "pi ./ x"
86
+ assert julia_code(x/3) == "x / 3"
87
+ assert julia_code(x/pi) == "x / pi"
88
+ assert julia_code(x*y) == "x .* y"
89
+ assert julia_code(3*x*y) == "3 * x .* y"
90
+ assert julia_code(3*pi*x*y) == "3 * pi * x .* y"
91
+ assert julia_code(x/y) == "x ./ y"
92
+ assert julia_code(3*x/y) == "3 * x ./ y"
93
+ assert julia_code(x*y/z) == "x .* y ./ z"
94
+ assert julia_code(x/y*z) == "x .* z ./ y"
95
+ assert julia_code(1/x/y) == "1 ./ (x .* y)"
96
+ assert julia_code(2*pi*x/y/z) == "2 * pi * x ./ (y .* z)"
97
+ assert julia_code(3*pi/x) == "3 * pi ./ x"
98
+ assert julia_code(S(3)/5) == "3 // 5"
99
+ assert julia_code(S(3)/5*x) == "(3 // 5) * x"
100
+ assert julia_code(x/y/z) == "x ./ (y .* z)"
101
+ assert julia_code((x+y)/z) == "(x + y) ./ z"
102
+ assert julia_code((x+y)/(z+x)) == "(x + y) ./ (x + z)"
103
+ assert julia_code((x+y)/EulerGamma) == "(x + y) / eulergamma"
104
+ assert julia_code(x/3/pi) == "x / (3 * pi)"
105
+ assert julia_code(S(3)/5*x*y/pi) == "(3 // 5) * x .* y / pi"
106
+
107
+
108
+ def test_mix_number_pow_symbols():
109
+ assert julia_code(pi**3) == 'pi ^ 3'
110
+ assert julia_code(x**2) == 'x .^ 2'
111
+ assert julia_code(x**(pi**3)) == 'x .^ (pi ^ 3)'
112
+ assert julia_code(x**y) == 'x .^ y'
113
+ assert julia_code(x**(y**z)) == 'x .^ (y .^ z)'
114
+ assert julia_code((x**y)**z) == '(x .^ y) .^ z'
115
+
116
+
117
+ def test_imag():
118
+ I = S('I')
119
+ assert julia_code(I) == "im"
120
+ assert julia_code(5*I) == "5im"
121
+ assert julia_code((S(3)/2)*I) == "(3 // 2) * im"
122
+ assert julia_code(3+4*I) == "3 + 4im"
123
+
124
+
125
+ def test_constants():
126
+ assert julia_code(pi) == "pi"
127
+ assert julia_code(oo) == "Inf"
128
+ assert julia_code(-oo) == "-Inf"
129
+ assert julia_code(S.NegativeInfinity) == "-Inf"
130
+ assert julia_code(S.NaN) == "NaN"
131
+ assert julia_code(S.Exp1) == "e"
132
+ assert julia_code(exp(1)) == "e"
133
+
134
+
135
+ def test_constants_other():
136
+ assert julia_code(2*GoldenRatio) == "2 * golden"
137
+ assert julia_code(2*Catalan) == "2 * catalan"
138
+ assert julia_code(2*EulerGamma) == "2 * eulergamma"
139
+
140
+
141
+ def test_boolean():
142
+ assert julia_code(x & y) == "x && y"
143
+ assert julia_code(x | y) == "x || y"
144
+ assert julia_code(~x) == "!x"
145
+ assert julia_code(x & y & z) == "x && y && z"
146
+ assert julia_code(x | y | z) == "x || y || z"
147
+ assert julia_code((x & y) | z) == "z || x && y"
148
+ assert julia_code((x | y) & z) == "z && (x || y)"
149
+
150
+
151
+ def test_Matrices():
152
+ assert julia_code(Matrix(1, 1, [10])) == "[10]"
153
+ A = Matrix([[1, sin(x/2), abs(x)],
154
+ [0, 1, pi],
155
+ [0, exp(1), ceiling(x)]]);
156
+ expected = ("[1 sin(x / 2) abs(x);\n"
157
+ "0 1 pi;\n"
158
+ "0 e ceil(x)]")
159
+ assert julia_code(A) == expected
160
+ # row and columns
161
+ assert julia_code(A[:,0]) == "[1, 0, 0]"
162
+ assert julia_code(A[0,:]) == "[1 sin(x / 2) abs(x)]"
163
+ # empty matrices
164
+ assert julia_code(Matrix(0, 0, [])) == 'zeros(0, 0)'
165
+ assert julia_code(Matrix(0, 3, [])) == 'zeros(0, 3)'
166
+ # annoying to read but correct
167
+ assert julia_code(Matrix([[x, x - y, -y]])) == "[x x - y -y]"
168
+
169
+
170
+ def test_vector_entries_hadamard():
171
+ # For a row or column, user might to use the other dimension
172
+ A = Matrix([[1, sin(2/x), 3*pi/x/5]])
173
+ assert julia_code(A) == "[1 sin(2 ./ x) (3 // 5) * pi ./ x]"
174
+ assert julia_code(A.T) == "[1, sin(2 ./ x), (3 // 5) * pi ./ x]"
175
+
176
+
177
+ @XFAIL
178
+ def test_Matrices_entries_not_hadamard():
179
+ # For Matrix with col >= 2, row >= 2, they need to be scalars
180
+ # FIXME: is it worth worrying about this? Its not wrong, just
181
+ # leave it user's responsibility to put scalar data for x.
182
+ A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]])
183
+ expected = ("[1 sin(2/x) 3*pi/(5*x);\n"
184
+ "1 2 x*y]") # <- we give x.*y
185
+ assert julia_code(A) == expected
186
+
187
+
188
+ def test_MatrixSymbol():
189
+ n = Symbol('n', integer=True)
190
+ A = MatrixSymbol('A', n, n)
191
+ B = MatrixSymbol('B', n, n)
192
+ assert julia_code(A*B) == "A * B"
193
+ assert julia_code(B*A) == "B * A"
194
+ assert julia_code(2*A*B) == "2 * A * B"
195
+ assert julia_code(B*2*A) == "2 * B * A"
196
+ assert julia_code(A*(B + 3*Identity(n))) == "A * (3 * eye(n) + B)"
197
+ assert julia_code(A**(x**2)) == "A ^ (x .^ 2)"
198
+ assert julia_code(A**3) == "A ^ 3"
199
+ assert julia_code(A**S.Half) == "A ^ (1 // 2)"
200
+
201
+
202
+ def test_special_matrices():
203
+ assert julia_code(6*Identity(3)) == "6 * eye(3)"
204
+
205
+
206
+ def test_containers():
207
+ assert julia_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
208
+ "Any[1, 2, 3, Any[4, 5, Any[6, 7]], 8, Any[9, 10], 11]"
209
+ assert julia_code((1, 2, (3, 4))) == "(1, 2, (3, 4))"
210
+ assert julia_code([1]) == "Any[1]"
211
+ assert julia_code((1,)) == "(1,)"
212
+ assert julia_code(Tuple(*[1, 2, 3])) == "(1, 2, 3)"
213
+ assert julia_code((1, x*y, (3, x**2))) == "(1, x .* y, (3, x .^ 2))"
214
+ # scalar, matrix, empty matrix and empty list
215
+ assert julia_code((1, eye(3), Matrix(0, 0, []), [])) == "(1, [1 0 0;\n0 1 0;\n0 0 1], zeros(0, 0), Any[])"
216
+
217
+
218
+ def test_julia_noninline():
219
+ source = julia_code((x+y)/Catalan, assign_to='me', inline=False)
220
+ expected = (
221
+ "const Catalan = %s\n"
222
+ "me = (x + y) / Catalan"
223
+ ) % Catalan.evalf(17)
224
+ assert source == expected
225
+
226
+
227
+ def test_julia_piecewise():
228
+ expr = Piecewise((x, x < 1), (x**2, True))
229
+ assert julia_code(expr) == "((x < 1) ? (x) : (x .^ 2))"
230
+ assert julia_code(expr, assign_to="r") == (
231
+ "r = ((x < 1) ? (x) : (x .^ 2))")
232
+ assert julia_code(expr, assign_to="r", inline=False) == (
233
+ "if (x < 1)\n"
234
+ " r = x\n"
235
+ "else\n"
236
+ " r = x .^ 2\n"
237
+ "end")
238
+ expr = Piecewise((x**2, x < 1), (x**3, x < 2), (x**4, x < 3), (x**5, True))
239
+ expected = ("((x < 1) ? (x .^ 2) :\n"
240
+ "(x < 2) ? (x .^ 3) :\n"
241
+ "(x < 3) ? (x .^ 4) : (x .^ 5))")
242
+ assert julia_code(expr) == expected
243
+ assert julia_code(expr, assign_to="r") == "r = " + expected
244
+ assert julia_code(expr, assign_to="r", inline=False) == (
245
+ "if (x < 1)\n"
246
+ " r = x .^ 2\n"
247
+ "elseif (x < 2)\n"
248
+ " r = x .^ 3\n"
249
+ "elseif (x < 3)\n"
250
+ " r = x .^ 4\n"
251
+ "else\n"
252
+ " r = x .^ 5\n"
253
+ "end")
254
+ # Check that Piecewise without a True (default) condition error
255
+ expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
256
+ raises(ValueError, lambda: julia_code(expr))
257
+
258
+
259
+ def test_julia_piecewise_times_const():
260
+ pw = Piecewise((x, x < 1), (x**2, True))
261
+ assert julia_code(2*pw) == "2 * ((x < 1) ? (x) : (x .^ 2))"
262
+ assert julia_code(pw/x) == "((x < 1) ? (x) : (x .^ 2)) ./ x"
263
+ assert julia_code(pw/(x*y)) == "((x < 1) ? (x) : (x .^ 2)) ./ (x .* y)"
264
+ assert julia_code(pw/3) == "((x < 1) ? (x) : (x .^ 2)) / 3"
265
+
266
+
267
+ def test_julia_matrix_assign_to():
268
+ A = Matrix([[1, 2, 3]])
269
+ assert julia_code(A, assign_to='a') == "a = [1 2 3]"
270
+ A = Matrix([[1, 2], [3, 4]])
271
+ assert julia_code(A, assign_to='A') == "A = [1 2;\n3 4]"
272
+
273
+
274
+ def test_julia_matrix_assign_to_more():
275
+ # assigning to Symbol or MatrixSymbol requires lhs/rhs match
276
+ A = Matrix([[1, 2, 3]])
277
+ B = MatrixSymbol('B', 1, 3)
278
+ C = MatrixSymbol('C', 2, 3)
279
+ assert julia_code(A, assign_to=B) == "B = [1 2 3]"
280
+ raises(ValueError, lambda: julia_code(A, assign_to=x))
281
+ raises(ValueError, lambda: julia_code(A, assign_to=C))
282
+
283
+
284
+ def test_julia_matrix_1x1():
285
+ A = Matrix([[3]])
286
+ B = MatrixSymbol('B', 1, 1)
287
+ C = MatrixSymbol('C', 1, 2)
288
+ assert julia_code(A, assign_to=B) == "B = [3]"
289
+ # FIXME?
290
+ #assert julia_code(A, assign_to=x) == "x = [3]"
291
+ raises(ValueError, lambda: julia_code(A, assign_to=C))
292
+
293
+
294
+ def test_julia_matrix_elements():
295
+ A = Matrix([[x, 2, x*y]])
296
+ assert julia_code(A[0, 0]**2 + A[0, 1] + A[0, 2]) == "x .^ 2 + x .* y + 2"
297
+ A = MatrixSymbol('AA', 1, 3)
298
+ assert julia_code(A) == "AA"
299
+ assert julia_code(A[0, 0]**2 + sin(A[0,1]) + A[0,2]) == \
300
+ "sin(AA[1,2]) + AA[1,1] .^ 2 + AA[1,3]"
301
+ assert julia_code(sum(A)) == "AA[1,1] + AA[1,2] + AA[1,3]"
302
+
303
+
304
+ def test_julia_boolean():
305
+ assert julia_code(True) == "true"
306
+ assert julia_code(S.true) == "true"
307
+ assert julia_code(False) == "false"
308
+ assert julia_code(S.false) == "false"
309
+
310
+
311
+ def test_julia_not_supported():
312
+ assert julia_code(S.ComplexInfinity) == (
313
+ "# Not supported in Julia:\n"
314
+ "# ComplexInfinity\n"
315
+ "zoo"
316
+ )
317
+ f = Function('f')
318
+ assert julia_code(f(x).diff(x)) == (
319
+ "# Not supported in Julia:\n"
320
+ "# Derivative\n"
321
+ "Derivative(f(x), x)"
322
+ )
323
+
324
+
325
+ def test_trick_indent_with_end_else_words():
326
+ # words starting with "end" or "else" do not confuse the indenter
327
+ t1 = S('endless');
328
+ t2 = S('elsewhere');
329
+ pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True))
330
+ assert julia_code(pw, inline=False) == (
331
+ "if (x < 0)\n"
332
+ " endless\n"
333
+ "elseif (x <= 1)\n"
334
+ " elsewhere\n"
335
+ "else\n"
336
+ " 1\n"
337
+ "end")
338
+
339
+
340
+ def test_haramard():
341
+ A = MatrixSymbol('A', 3, 3)
342
+ B = MatrixSymbol('B', 3, 3)
343
+ v = MatrixSymbol('v', 3, 1)
344
+ h = MatrixSymbol('h', 1, 3)
345
+ C = HadamardProduct(A, B)
346
+ assert julia_code(C) == "A .* B"
347
+ assert julia_code(C*v) == "(A .* B) * v"
348
+ assert julia_code(h*C*v) == "h * (A .* B) * v"
349
+ assert julia_code(C*A) == "(A .* B) * A"
350
+ # mixing Hadamard and scalar strange b/c we vectorize scalars
351
+ assert julia_code(C*x*y) == "(x .* y) * (A .* B)"
352
+
353
+
354
+ def test_sparse():
355
+ M = SparseMatrix(5, 6, {})
356
+ M[2, 2] = 10;
357
+ M[1, 2] = 20;
358
+ M[1, 3] = 22;
359
+ M[0, 3] = 30;
360
+ M[3, 0] = x*y;
361
+ assert julia_code(M) == (
362
+ "sparse([4, 2, 3, 1, 2], [1, 3, 3, 4, 4], [x .* y, 20, 10, 30, 22], 5, 6)"
363
+ )
364
+
365
+
366
+ def test_specfun():
367
+ n = Symbol('n')
368
+ for f in [besselj, bessely, besseli, besselk]:
369
+ assert julia_code(f(n, x)) == f.__name__ + '(n, x)'
370
+ for f in [airyai, airyaiprime, airybi, airybiprime]:
371
+ assert julia_code(f(x)) == f.__name__ + '(x)'
372
+ assert julia_code(hankel1(n, x)) == 'hankelh1(n, x)'
373
+ assert julia_code(hankel2(n, x)) == 'hankelh2(n, x)'
374
+ assert julia_code(jn(n, x)) == 'sqrt(2) * sqrt(pi) * sqrt(1 ./ x) .* besselj(n + 1 // 2, x) / 2'
375
+ assert julia_code(yn(n, x)) == 'sqrt(2) * sqrt(pi) * sqrt(1 ./ x) .* bessely(n + 1 // 2, x) / 2'
376
+
377
+
378
+ def test_MatrixElement_printing():
379
+ # test cases for issue #11821
380
+ A = MatrixSymbol("A", 1, 3)
381
+ B = MatrixSymbol("B", 1, 3)
382
+ C = MatrixSymbol("C", 1, 3)
383
+
384
+ assert(julia_code(A[0, 0]) == "A[1,1]")
385
+ assert(julia_code(3 * A[0, 0]) == "3 * A[1,1]")
386
+
387
+ F = C[0, 0].subs(C, A - B)
388
+ assert(julia_code(F) == "(A - B)[1,1]")
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_lambdarepr.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.expr import Expr
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.functions.elementary.piecewise import Piecewise
6
+ from sympy.functions.elementary.trigonometric import sin
7
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix
8
+ from sympy.sets.sets import Interval
9
+ from sympy.utilities.lambdify import lambdify
10
+ from sympy.testing.pytest import raises
11
+
12
+ from sympy.printing.tensorflow import TensorflowPrinter
13
+ from sympy.printing.lambdarepr import lambdarepr, LambdaPrinter, NumExprPrinter
14
+
15
+
16
+ x, y, z = symbols("x,y,z")
17
+ i, a, b = symbols("i,a,b")
18
+ j, c, d = symbols("j,c,d")
19
+
20
+
21
+ def test_basic():
22
+ assert lambdarepr(x*y) == "x*y"
23
+ assert lambdarepr(x + y) in ["y + x", "x + y"]
24
+ assert lambdarepr(x**y) == "x**y"
25
+
26
+
27
+ def test_matrix():
28
+ # Test printing a Matrix that has an element that is printed differently
29
+ # with the LambdaPrinter than with the StrPrinter.
30
+ e = x % 2
31
+ assert lambdarepr(e) != str(e)
32
+ assert lambdarepr(Matrix([e])) == 'ImmutableDenseMatrix([[x % 2]])'
33
+
34
+
35
+ def test_piecewise():
36
+ # In each case, test eval() the lambdarepr() to make sure there are a
37
+ # correct number of parentheses. It will give a SyntaxError if there aren't.
38
+
39
+ h = "lambda x: "
40
+
41
+ p = Piecewise((x, x < 0))
42
+ l = lambdarepr(p)
43
+ eval(h + l)
44
+ assert l == "((x) if (x < 0) else None)"
45
+
46
+ p = Piecewise(
47
+ (1, x < 1),
48
+ (2, x < 2),
49
+ (0, True)
50
+ )
51
+ l = lambdarepr(p)
52
+ eval(h + l)
53
+ assert l == "((1) if (x < 1) else (2) if (x < 2) else (0))"
54
+
55
+ p = Piecewise(
56
+ (1, x < 1),
57
+ (2, x < 2),
58
+ )
59
+ l = lambdarepr(p)
60
+ eval(h + l)
61
+ assert l == "((1) if (x < 1) else (2) if (x < 2) else None)"
62
+
63
+ p = Piecewise(
64
+ (x, x < 1),
65
+ (x**2, Interval(3, 4, True, False).contains(x)),
66
+ (0, True),
67
+ )
68
+ l = lambdarepr(p)
69
+ eval(h + l)
70
+ assert l == "((x) if (x < 1) else (x**2) if (((x <= 4)) and ((x > 3))) else (0))"
71
+
72
+ p = Piecewise(
73
+ (x**2, x < 0),
74
+ (x, x < 1),
75
+ (2 - x, x >= 1),
76
+ (0, True), evaluate=False
77
+ )
78
+ l = lambdarepr(p)
79
+ eval(h + l)
80
+ assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\
81
+ " else (2 - x) if (x >= 1) else (0))"
82
+
83
+ p = Piecewise(
84
+ (x**2, x < 0),
85
+ (x, x < 1),
86
+ (2 - x, x >= 1), evaluate=False
87
+ )
88
+ l = lambdarepr(p)
89
+ eval(h + l)
90
+ assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\
91
+ " else (2 - x) if (x >= 1) else None)"
92
+
93
+ p = Piecewise(
94
+ (1, x >= 1),
95
+ (2, x >= 2),
96
+ (3, x >= 3),
97
+ (4, x >= 4),
98
+ (5, x >= 5),
99
+ (6, True)
100
+ )
101
+ l = lambdarepr(p)
102
+ eval(h + l)
103
+ assert l == "((1) if (x >= 1) else (2) if (x >= 2) else (3) if (x >= 3)"\
104
+ " else (4) if (x >= 4) else (5) if (x >= 5) else (6))"
105
+
106
+ p = Piecewise(
107
+ (1, x <= 1),
108
+ (2, x <= 2),
109
+ (3, x <= 3),
110
+ (4, x <= 4),
111
+ (5, x <= 5),
112
+ (6, True)
113
+ )
114
+ l = lambdarepr(p)
115
+ eval(h + l)
116
+ assert l == "((1) if (x <= 1) else (2) if (x <= 2) else (3) if (x <= 3)"\
117
+ " else (4) if (x <= 4) else (5) if (x <= 5) else (6))"
118
+
119
+ p = Piecewise(
120
+ (1, x > 1),
121
+ (2, x > 2),
122
+ (3, x > 3),
123
+ (4, x > 4),
124
+ (5, x > 5),
125
+ (6, True)
126
+ )
127
+ l = lambdarepr(p)
128
+ eval(h + l)
129
+ assert l =="((1) if (x > 1) else (2) if (x > 2) else (3) if (x > 3)"\
130
+ " else (4) if (x > 4) else (5) if (x > 5) else (6))"
131
+
132
+ p = Piecewise(
133
+ (1, x < 1),
134
+ (2, x < 2),
135
+ (3, x < 3),
136
+ (4, x < 4),
137
+ (5, x < 5),
138
+ (6, True)
139
+ )
140
+ l = lambdarepr(p)
141
+ eval(h + l)
142
+ assert l == "((1) if (x < 1) else (2) if (x < 2) else (3) if (x < 3)"\
143
+ " else (4) if (x < 4) else (5) if (x < 5) else (6))"
144
+
145
+ p = Piecewise(
146
+ (Piecewise(
147
+ (1, x > 0),
148
+ (2, True)
149
+ ), y > 0),
150
+ (3, True)
151
+ )
152
+ l = lambdarepr(p)
153
+ eval(h + l)
154
+ assert l == "((((1) if (x > 0) else (2))) if (y > 0) else (3))"
155
+
156
+
157
+ def test_sum__1():
158
+ # In each case, test eval() the lambdarepr() to make sure that
159
+ # it evaluates to the same results as the symbolic expression
160
+ s = Sum(x ** i, (i, a, b))
161
+ l = lambdarepr(s)
162
+ assert l == "(builtins.sum(x**i for i in range(a, b+1)))"
163
+
164
+ args = x, a, b
165
+ f = lambdify(args, s)
166
+ v = 2, 3, 8
167
+ assert f(*v) == s.subs(zip(args, v)).doit()
168
+
169
+ def test_sum__2():
170
+ s = Sum(i * x, (i, a, b))
171
+ l = lambdarepr(s)
172
+ assert l == "(builtins.sum(i*x for i in range(a, b+1)))"
173
+
174
+ args = x, a, b
175
+ f = lambdify(args, s)
176
+ v = 2, 3, 8
177
+ assert f(*v) == s.subs(zip(args, v)).doit()
178
+
179
+
180
+ def test_multiple_sums():
181
+ s = Sum(i * x + j, (i, a, b), (j, c, d))
182
+
183
+ l = lambdarepr(s)
184
+ assert l == "(builtins.sum(i*x + j for i in range(a, b+1) for j in range(c, d+1)))"
185
+
186
+ args = x, a, b, c, d
187
+ f = lambdify(args, s)
188
+ vals = 2, 3, 4, 5, 6
189
+ f_ref = s.subs(zip(args, vals)).doit()
190
+ f_res = f(*vals)
191
+ assert f_res == f_ref
192
+
193
+
194
+ def test_sqrt():
195
+ prntr = LambdaPrinter({'standard' : 'python3'})
196
+ assert prntr._print_Pow(sqrt(x), rational=False) == 'sqrt(x)'
197
+ assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)'
198
+
199
+
200
+ def test_settings():
201
+ raises(TypeError, lambda: lambdarepr(sin(x), method="garbage"))
202
+
203
+
204
+ def test_numexpr():
205
+ # test ITE rewrite as Piecewise
206
+ from sympy.logic.boolalg import ITE
207
+ expr = ITE(x > 0, True, False, evaluate=False)
208
+ assert NumExprPrinter().doprint(expr) == \
209
+ "numexpr.evaluate('where((x > 0), True, False)', truediv=True)"
210
+
211
+ from sympy.codegen.ast import Return, FunctionDefinition, Variable, Assignment
212
+ func_def = FunctionDefinition(None, 'foo', [Variable(x)], [Assignment(y,x), Return(y**2)])
213
+ expected = "def foo(x):\n"\
214
+ " y = numexpr.evaluate('x', truediv=True)\n"\
215
+ " return numexpr.evaluate('y**2', truediv=True)"
216
+ assert NumExprPrinter().doprint(func_def) == expected
217
+
218
+
219
+ class CustomPrintedObject(Expr):
220
+ def _lambdacode(self, printer):
221
+ return 'lambda'
222
+
223
+ def _tensorflowcode(self, printer):
224
+ return 'tensorflow'
225
+
226
+ def _numpycode(self, printer):
227
+ return 'numpy'
228
+
229
+ def _numexprcode(self, printer):
230
+ return 'numexpr'
231
+
232
+ def _mpmathcode(self, printer):
233
+ return 'mpmath'
234
+
235
+
236
+ def test_printmethod():
237
+ # In each case, printmethod is called to test
238
+ # its working
239
+
240
+ obj = CustomPrintedObject()
241
+ assert LambdaPrinter().doprint(obj) == 'lambda'
242
+ assert TensorflowPrinter().doprint(obj) == 'tensorflow'
243
+ assert NumExprPrinter().doprint(obj) == "numexpr.evaluate('numexpr', truediv=True)"
244
+
245
+ assert NumExprPrinter().doprint(Piecewise((y, x >= 0), (z, x < 0))) == \
246
+ "numexpr.evaluate('where((x >= 0), y, z)', truediv=True)"
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/test_latex.py ADDED
The diff for this file is too large to render. See raw diff