Debian Codegraph @

brian2/parsing/bast.py

raw
1 """
2 Brian AST representation
3
4 This is a standard Python AST representation with additional information added.
5 """
6
7 import ast
8 import weakref
9
10 import numpy
11
12 from brian2.utils.logger import get_logger
13
14 __all__ = ["brian_ast", "BrianASTRenderer", "dtype_hierarchy"]
15
16
17 logger = get_logger(__name__)
18
19 # This codifies the idea that operations involving e.g. boolean and integer will end up
20 # as integer. In general the output type will be the max of the hierarchy values here.
21 dtype_hierarchy = {
22 "boolean": 0,
23 "integer": 1,
24 "float": 2,
25 }
26 # This is just so you can invert from number to string
27 for tc, i in dict(dtype_hierarchy).items():
28 dtype_hierarchy[i] = tc
29
30
31 def is_boolean(value):
32 return isinstance(value, bool)
33
34
35 def is_integer(value):
36 return isinstance(value, (int, numpy.integer))
37
38
39 def is_float(value):
40 return isinstance(value, (float, numpy.float32, numpy.float64))
41
42
43 def brian_dtype_from_value(value):
44 """
45 Returns 'boolean', 'integer' or 'float'
46 """
47 if is_float(value):
48 return "float"
49 elif is_integer(value):
50 return "integer"
51 elif is_boolean(value):
52 return "boolean"
53 raise TypeError(f"Unknown dtype for value {str(value)}")
54
55
56 # The following functions are called very often during the optimisation process
57 # so we don't use numpy.issubdtype but instead a precalculated list of all
58 # standard types
59
60 bool_dtype = numpy.dtype(bool)
61
62
63 def is_boolean_dtype(obj):
64 return numpy.dtype(obj) is bool_dtype
65
66
67 integer_dtypes = {numpy.dtype(c) for c in numpy.typecodes["AllInteger"]}
68
69
70 def is_integer_dtype(obj):
71 return numpy.dtype(obj) in integer_dtypes
72
73
74 float_dtypes = {numpy.dtype(c) for c in numpy.typecodes["AllFloat"]}
75
76
77 def is_float_dtype(obj):
78 return numpy.dtype(obj) in float_dtypes
79
80
81 def brian_dtype_from_dtype(dtype):
82 """
83 Returns 'boolean', 'integer' or 'float'
84 """
85 if is_float_dtype(dtype):
86 return "float"
87 elif is_integer_dtype(dtype):
88 return "integer"
89 elif is_boolean_dtype(dtype):
90 return "boolean"
91 raise TypeError(f"Unknown dtype: {str(dtype)}")
92
93
94 def brian_ast(expr, variables):
95 """
96 Returns an AST tree representation with additional information
97
98 Each node will be a standard Python ``ast`` node with the
99 following additional attributes:
100
101 ``dtype``
102 One of ``'boolean'``, ``'integer'`` or ``'float'``, referring to the data type
103 of the value of this node.
104 ``scalar``
105 Either ``True`` or ``False`` if the node uses any vector-valued variables.
106 ``complexity``
107 An integer representation of the computational complexity of the node. This
108 is a very rough representation used for things like ``2*(x+y)`` is less
109 complex than ``2*x+2*y`` and ``exp(x)`` is more complex than ``2*x`` but
110 shouldn't be relied on for fine distinctions between expressions.
111
112 Parameters
113 ----------
114 expr : str
115 The expression to convert into an AST representation
116 variables : dict
117 The dictionary of `Variable` objects used in the expression.
118 """
119 node = ast.parse(expr, mode="eval").body
120 renderer = BrianASTRenderer(variables)
121 return renderer.render_node(node)
122
123
124 class BrianASTRenderer:
125 """
126 This class is modelled after `NodeRenderer` - see there for details.
127 """
128
129 def __init__(self, variables, copy_variables=True):
130 if copy_variables:
131 self.variables = variables.copy()
132 else:
133 self.variables = variables
134
135 def render_node(self, node):
136 nodename = node.__class__.__name__
137 methname = f"render_{nodename}"
138 try:
139 return getattr(self, methname)(node)
140 except AttributeError:
141 raise SyntaxError(f"Unknown syntax: {nodename}") from None
142
143 def render_NameConstant(self, node):
144 if node.value is not True and node.value is not False:
145 raise SyntaxError(f"Unknown NameConstant {str(node.value)}")
146 # NameConstant only used for True and False and None, and we don't support None
147 node.dtype = "boolean"
148 node.scalar = True
149 node.complexity = 0
150 node.stateless = True
151 return node
152
153 def render_Name(self, node):
154 node.complexity = 0
155 if node.id == "True" or node.id == "False":
156 node.dtype = "boolean"
157 node.scalar = True
158 elif node.id in self.variables:
159 var = self.variables[node.id]
160 dtype = var.dtype
161 node.dtype = brian_dtype_from_dtype(dtype)
162 node.scalar = var.scalar
163 else: # don't think we need to handle other names (pi, e, inf)?
164 node.dtype = "float"
165 node.scalar = True # I think this assumption is OK, but not certain
166 node.stateless = True
167 return node
168
169 def render_Num(self, node):
170 node.complexity = 0
171 node.dtype = brian_dtype_from_value(node.value)
172 node.scalar = True
173 node.stateless = True
174 return node
175
176 def render_Constant(self, node): # For literals in Python >= 3.8
177 if node.value is True or node.value is False or node.value is None:
178 return self.render_NameConstant(node)
179 else:
180 return self.render_Num(node)
181
182 def render_Call(self, node):
183 if len(node.keywords):
184 raise ValueError("Keyword arguments not supported.")
185 elif getattr(node, "starargs", None) is not None:
186 raise ValueError("Variable number of arguments not supported")
187 elif getattr(node, "kwargs", None) is not None:
188 raise ValueError("Keyword arguments not supported")
189 args = []
190 for subnode in node.args:
191 subnode.parent = weakref.proxy(node)
192 subnode = self.render_node(subnode)
193 args.append(subnode)
194 node.args = args
195 node.dtype = "float" # default dtype
196 # Condition for scalarity of function call: stateless and arguments are scalar
197 node.scalar = False
198 if node.func.id in self.variables:
199 funcvar = self.variables[node.func.id]
200 # sometimes this attribute doesn't exist, if so assume it's not stateless
201 node.stateless = getattr(funcvar, "stateless", False)
202 node.auto_vectorise = getattr(funcvar, "auto_vectorise", False)
203 if node.stateless and not node.auto_vectorise:
204 node.scalar = all(subnode.scalar for subnode in node.args)
205 # check that argument types are valid
206 node_arg_types = [subnode.dtype for subnode in node.args]
207 for subnode, argtype in zip(node.args, funcvar._arg_types, strict=True):
208 if argtype != "any" and argtype != subnode.dtype:
209 raise TypeError(
210 f"Function '{node.func.id}' takes arguments with "
211 f"types {funcvar._arg_types} but "
212 f"received {node_arg_types}."
213 )
214 # compute return type
215 return_type = funcvar._return_type
216 if return_type == "highest":
217 return_type = dtype_hierarchy[
218 max(dtype_hierarchy[nat] for nat in node_arg_types)
219 ]
220 node.dtype = return_type
221 else:
222 node.stateless = False
223 # we leave node.func because it is an ast.Name object that doesn't have a dtype
224 # TODO: variable complexity for function calls?
225 node.complexity = 20 + sum(subnode.complexity for subnode in node.args)
226 return node
227
228 def render_BinOp(self, node):
229 node.left.parent = weakref.proxy(node)
230 node.right.parent = weakref.proxy(node)
231 node.left = self.render_node(node.left)
232 node.right = self.render_node(node.right)
233 # TODO: we could capture some syntax errors here, e.g. bool+bool
234 # captures, e.g. int+float->float
235 newdtype = dtype_hierarchy[
236 max(dtype_hierarchy[subnode.dtype] for subnode in [node.left, node.right])
237 ]
238 if node.op.__class__.__name__ == "Div":
239 # Division turns integers into floating point values
240 newdtype = "float"
241 node.dtype = newdtype
242 node.scalar = node.left.scalar and node.right.scalar
243 node.complexity = 1 + node.left.complexity + node.right.complexity
244 node.stateless = node.left.stateless and node.right.stateless
245 return node
246
247 def render_BoolOp(self, node):
248 values = []
249 for subnode in node.values:
250 subnode.parent = node
251 subnode = self.render_node(subnode)
252 values.append(subnode)
253 node.values = values
254 node.dtype = "boolean"
255 for subnode in node.values:
256 if subnode.dtype != "boolean":
257 raise TypeError("Boolean operator acting on non-booleans")
258 node.scalar = all(subnode.scalar for subnode in node.values)
259 node.complexity = 1 + sum(subnode.complexity for subnode in node.values)
260 node.stateless = all(subnode.stateless for subnode in node.values)
261 return node
262
263 def render_Compare(self, node):
264 node.left = self.render_node(node.left)
265 comparators = []
266 for subnode in node.comparators:
267 subnode.parent = node
268 subnode = self.render_node(subnode)
269 comparators.append(subnode)
270 node.comparators = comparators
271 node.dtype = "boolean"
272 comparators = [node.left] + node.comparators
273 node.scalar = all(subnode.scalar for subnode in comparators)
274 node.complexity = 1 + sum(subnode.complexity for subnode in comparators)
275 node.stateless = node.left.stateless and all(
276 c.stateless for c in node.comparators
277 )
278 return node
279
280 def render_UnaryOp(self, node):
281 node.operand.parent = node
282 node.operand = self.render_node(node.operand)
283 node.dtype = node.operand.dtype
284 if node.dtype == "boolean" and node.op.__class__.__name__ != "Not":
285 raise TypeError(
286 f"Unary operator {node.op.__class__.__name__} does not apply to boolean"
287 " types"
288 )
289 node.scalar = node.operand.scalar
290 node.complexity = 1 + node.operand.complexity
291 node.stateless = node.operand.stateless
292 return node