-
Notifications
You must be signed in to change notification settings - Fork 223
/
printer.py
200 lines (156 loc) · 6.13 KB
/
printer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
Utilities to turn SymPy objects into C strings.
"""
import numpy as np
from mpmath.libmp import prec_to_dps, to_str
from sympy.logic.boolalg import BooleanFunction
from sympy.printing.precedence import PRECEDENCE_VALUES, precedence
from sympy.printing.c import C99CodePrinter
__all__ = ['ccode']
class CodePrinter(C99CodePrinter):
"""
Decorator for sympy.printing.ccode.CCodePrinter.
Parameters
----------
settings : dict
Options for code printing.
"""
def __init__(self, dtype=np.float32, settings={}):
self.dtype = dtype
C99CodePrinter.__init__(self, settings)
def parenthesize(self, item, level, strict=False):
if isinstance(item, BooleanFunction):
return "(%s)" % self._print(item)
return super().parenthesize(item, level, strict=strict)
def _print_Function(self, expr):
# There exist no unknown Functions
if expr.func.__name__ not in self.known_functions:
self.known_functions[expr.func.__name__] = expr.func.__name__
return super(CodePrinter, self)._print_Function(expr)
def _print_CondEq(self, expr):
return "%s == %s" % (self._print(expr.lhs), self._print(expr.rhs))
def _print_Indexed(self, expr):
"""
Print an Indexed as a C-like multidimensional array.
Examples
--------
U[t,x,y,z] -> U[t][x][y][z]
"""
return self._print(expr.base.label) \
+ ''.join(['[' + self._print(x) + ']' for x in expr.indices])
def _print_FIndexed(self, expr):
"""
Print an FIndexed, that is a special Indexed, as a C-like multiarguments function.
Examples
--------
U[t,x,y,z] -> U(t,x,y,z)
"""
return self._print(expr.base.label) \
+ '(%s)' % ', '.join(self._print(x) for x in expr.indices)
def _print_Rational(self, expr):
"""Print a Rational as a C-like float/float division."""
# This method and _print_Float below forcefully add a F to any
# literals generated in code. This forces all float literals
# to be 32-bit floats.
# http://en.cppreference.com/w/cpp/language/floating_literal
p, q = int(expr.p), int(expr.q)
if self.dtype == np.float64:
return '%d.0/%d.0' % (p, q)
else:
return '%d.0F/%d.0F' % (p, q)
def _print_Pow(self, expr):
# Need to override because of issue #1627
# E.g., (Pow(h_x, -1) AND h_x.dtype == np.float32) => 1.0F/h_x
try:
if expr.exp == -1 and self.dtype == np.float32:
PREC = precedence(expr)
return '1.0F/%s' % self.parenthesize(expr.base, PREC)
except AttributeError:
pass
return super()._print_Pow(expr)
def _print_Mod(self, expr):
"""Print a Mod as a C-like %-based operation."""
args = map(ccode, expr.args)
args = ['('+x+')' for x in args]
result = '%'.join(args)
return result
def _print_Float(self, expr):
"""Print a Float in C-like scientific notation."""
prec = expr._prec
if prec < 5:
dps = 0
else:
dps = prec_to_dps(expr._prec)
if self._settings["full_prec"] is True:
strip = False
elif self._settings["full_prec"] is False:
strip = True
elif self._settings["full_prec"] == "auto":
strip = self._print_level > 1
rv = to_str(expr._mpf_, dps, strip_zeros=strip, max_fixed=-2, min_fixed=2)
if rv.startswith('-.0'):
rv = '-0.' + rv[3:]
elif rv.startswith('.0'):
rv = '0.' + rv[2:]
if self.dtype == np.float32:
rv = rv + 'F'
return rv
def _print_Differentiable(self, expr):
return "(" + self._print(expr._expr) + ")"
_print_EvalDerivative = C99CodePrinter._print_Add
def _print_CallFromPointer(self, expr):
indices = [self._print(i) for i in expr.params]
return "%s->%s(%s)" % (expr.pointer, expr.call, ', '.join(indices))
def _print_FieldFromPointer(self, expr):
return "%s->%s" % (expr.pointer, expr.field)
def _print_FieldFromComposite(self, expr):
return "%s.%s" % (expr.pointer, expr.field)
def _print_ListInitializer(self, expr):
return "{%s}" % ', '.join([self._print(i) for i in expr.params])
def _print_IndexedPointer(self, expr):
return "%s%s" % (expr.base, ''.join('[%s]' % self._print(i) for i in expr.index))
def _print_IntDiv(self, expr):
lhs = self._print(expr.lhs)
if not expr.lhs.is_Atom:
lhs = '(%s)' % (lhs)
rhs = self._print(expr.rhs)
PREC = precedence(expr)
return self.parenthesize("%s / %s" % (lhs, rhs), PREC)
def _print_InlineIf(self, expr):
cond = self._print(expr.cond)
true_expr = self._print(expr.true_expr)
false_expr = self._print(expr.false_expr)
PREC = precedence(expr)
return self.parenthesize("(%s) ? %s : %s" % (cond, true_expr, false_expr), PREC)
def _print_UnaryOp(self, expr):
return expr.__str__()
_print_DefFunction = _print_UnaryOp
_print_MacroArgument = _print_UnaryOp
_print_IndexedBase = _print_UnaryOp
_print_IndexSum = _print_UnaryOp
_print_Keyword = _print_UnaryOp
def _print_TrigonometricFunction(self, expr):
func_name = str(expr.func)
if self.dtype == np.float32:
func_name += 'f'
return func_name + '(' + self._print(*expr.args) + ')'
def _print_Basic(self, expr):
return str(expr)
# Always parenthesize IntDiv and InlineIf within expressions
PRECEDENCE_VALUES['IntDiv'] = 1
PRECEDENCE_VALUES['InlineIf'] = 1
def ccode(expr, dtype=np.float32, **settings):
"""Generate C++ code from an expression.
Parameters
----------
expr : expr-like
The expression to be printed.
settings : dict
Options for code printing.
Returns
-------
str
The resulting code as a C++ string. If something went south, returns
the input ``expr`` itself.
"""
return CodePrinter(dtype=dtype, settings=settings).doprint(expr, None)