Debian Codegraph @

brian2/codegen/generators/numpy_generator.py

raw
1 import itertools
2
3 import numpy as np
4
5 from brian2.core.functions import DEFAULT_FUNCTIONS, timestep
6 from brian2.core.variables import ArrayVariable
7 from brian2.parsing.bast import brian_dtype_from_dtype
8 from brian2.parsing.rendering import NumpyNodeRenderer
9 from brian2.utils.logger import get_logger
10 from brian2.utils.stringtools import get_identifiers, indent, word_substitute
11
12 from .base import CodeGenerator
13
14 __all__ = ["NumpyCodeGenerator"]
15
16
17 logger = get_logger(__name__)
18
19
20 class VectorisationError(Exception):
21 pass
22
23
24 class NumpyCodeGenerator(CodeGenerator):
25 """
26 Numpy language
27
28 Essentially Python but vectorised.
29 """
30
31 class_name = "numpy"
32
33 _use_ufunc_at_vectorisation = True # allow this to be off for testing only
34
35 def translate_expression(self, expr):
36 expr = word_substitute(expr, self.func_name_replacements)
37 return (
38 NumpyNodeRenderer(auto_vectorise=self.auto_vectorise)
39 .render_expr(expr, self.variables)
40 .strip()
41 )
42
43 def translate_statement(self, statement):
44 # TODO: optimisation, translate arithmetic to a sequence of inplace
45 # operations like a=b+c -> add(b, c, a)
46 var, op, expr, comment = (
47 statement.var,
48 statement.op,
49 statement.expr,
50 statement.comment,
51 )
52 if op == ":=":
53 op = "="
54 # For numpy we replace complex expressions involving a single boolean variable into a
55 # where(boolvar, expr_if_true, expr_if_false)
56 if (
57 statement.used_boolean_variables is not None
58 and len(statement.used_boolean_variables) == 1
59 and brian_dtype_from_dtype(statement.dtype) == "float"
60 and statement.complexity_std > sum(statement.complexities.values())
61 ):
62 used_boolvars = statement.used_boolean_variables
63 bool_simp = statement.boolean_simplified_expressions
64 boolvar = used_boolvars[0]
65 for bool_assigns, simp_expr in bool_simp.items():
66 _, boolval = bool_assigns[0]
67 if boolval:
68 expr_true = simp_expr
69 else:
70 expr_false = simp_expr
71 code = f"{var} {op} _numpy.where({boolvar}, {expr_true}, {expr_false})"
72 else:
73 code = f"{var} {op} {self.translate_expression(expr)}"
74 if len(comment):
75 code += f" # {comment}"
76 return code
77
78 def ufunc_at_vectorisation(
79 self,
80 statement,
81 variables,
82 indices,
83 conditional_write_vars,
84 created_vars,
85 used_variables,
86 ):
87 if not self._use_ufunc_at_vectorisation:
88 raise VectorisationError()
89 # Avoids circular import
90 from brian2.devices.device import device
91
92 # See https://github.com/brian-team/brian2/pull/531 for explanation
93 used = set(get_identifiers(statement.expr))
94 used = used.intersection(
95 k for k in list(variables.keys()) if k in indices and indices[k] != "_idx"
96 )
97 used_variables.update(used)
98 if statement.var in used_variables:
99 raise VectorisationError()
100 expr = NumpyNodeRenderer(auto_vectorise=self.auto_vectorise).render_expr(
101 statement.expr
102 )
103
104 if (
105 statement.op == ":="
106 or indices[statement.var] == "_idx"
107 or not statement.inplace
108 ):
109 if statement.op == ":=":
110 op = "="
111 else:
112 op = statement.op
113 line = f"{statement.var} {op} {expr}"
114 elif statement.inplace:
115 if statement.op == "+=":
116 ufunc_name = "_numpy.add"
117 elif statement.op == "*=":
118 ufunc_name = "_numpy.multiply"
119 elif statement.op == "/=":
120 ufunc_name = "_numpy.divide"
121 elif statement.op == "-=":
122 ufunc_name = "_numpy.subtract"
123 else:
124 raise VectorisationError()
125 array_name = device.get_array_name(variables[statement.var])
126 idx = indices[statement.var]
127 line = f"{ufunc_name}.at({array_name}, {idx}, {expr})"
128 line = self.conditional_write(
129 line,
130 statement,
131 variables,
132 conditional_write_vars=conditional_write_vars,
133 created_vars=created_vars,
134 )
135 else:
136 raise VectorisationError()
137
138 if len(statement.comment):
139 line += f" # {statement.comment}"
140
141 return line
142
143 def vectorise_code(self, statements, variables, variable_indices, index="_idx"):
144 created_vars = {stmt.var for stmt in statements if stmt.op == ":="}
145 try:
146 lines = []
147 used_variables = set()
148 for statement in statements:
149 lines.append(
150 "# Abstract code: "
151 f" {statement.var} {statement.op} {statement.expr}"
152 )
153 # We treat every statement individually with its own read and write code
154 # to be on the safe side
155 read, write, indices, conditional_write_vars = self.arrays_helper(
156 [statement]
157 )
158 # We make sure that we only add code to `lines` after it went
159 # through completely
160 ufunc_lines = []
161 # No need to load a variable if it is only in read because of
162 # the in-place operation
163 if (
164 statement.inplace
165 and variable_indices[statement.var] != "_idx"
166 and statement.var not in get_identifiers(statement.expr)
167 ):
168 read = read - {statement.var}
169 ufunc_lines.extend(
170 self.read_arrays(read, write, indices, variables, variable_indices)
171 )
172 ufunc_lines.append(
173 self.ufunc_at_vectorisation(
174 statement,
175 variables,
176 variable_indices,
177 conditional_write_vars,
178 created_vars,
179 used_variables,
180 )
181 )
182 # Do not write back such values, the ufuncs have modified the
183 # underlying array already
184 if statement.inplace and variable_indices[statement.var] != "_idx":
185 write = write - {statement.var}
186 ufunc_lines.extend(
187 self.write_arrays(
188 [statement], read, write, variables, variable_indices
189 )
190 )
191 lines.extend(ufunc_lines)
192 except VectorisationError:
193 if self._use_ufunc_at_vectorisation:
194 logger.info(
195 "Failed to vectorise code, falling back on Python loop: note that"
196 " this will be very slow! Switch to another code generation target"
197 " for best performance (e.g. cython). First line is: "
198 + str(statements[0]),
199 once=True,
200 )
201 lines = []
202 lines.extend(
203 [
204 "_full_idx = _idx",
205 "for _idx in _full_idx:",
206 " _vectorisation_idx = _idx",
207 ]
208 )
209 read, write, indices, conditional_write_vars = self.arrays_helper(
210 statements
211 )
212 lines.extend(
213 indent(code)
214 for code in self.read_arrays(
215 read, write, indices, variables, variable_indices
216 )
217 )
218 for statement in statements:
219 line = self.translate_statement(statement)
220 if statement.var in conditional_write_vars:
221 lines.append(indent(f"if {conditional_write_vars[statement.var]}:"))
222 lines.append(indent(line, 2))
223 else:
224 lines.append(indent(line))
225 lines.extend(
226 indent(code)
227 for code in self.write_arrays(
228 statements, read, write, variables, variable_indices
229 )
230 )
231 return lines
232
233 def read_arrays(self, read, write, indices, variables, variable_indices):
234 # index and read arrays (index arrays first)
235 lines = []
236 for varname in itertools.chain(indices, read):
237 var = variables[varname]
238 index = variable_indices[varname]
239 # if index in iterate_all:
240 # line = '{varname} = {array_name}'
241 # else:
242 # line = '{varname} = {array_name}.take({index})'
243 # line = line.format(varname=varname, array_name=self.get_array_name(var), index=index)
244 line = f"{varname} = {self.get_array_name(var)}"
245 if index not in self.iterate_all:
246 line += f"[{index}]"
247 elif varname in write:
248 # avoid potential issues with aliased variables, see github #259
249 line += ".copy()"
250 lines.append(line)
251 return lines
252
253 def write_arrays(self, statements, read, write, variables, variable_indices):
254 # write arrays
255 lines = []
256 for varname in write:
257 var = variables[varname]
258 index_var = variable_indices[varname]
259 # check if all operations were inplace and we're operating on the
260 # whole vector, if so we don't need to write the array back
261 if index_var not in self.iterate_all or varname in read:
262 all_inplace = False
263 else:
264 all_inplace = True
265 for stmt in statements:
266 if stmt.var == varname and not stmt.inplace:
267 all_inplace = False
268 break
269 if not all_inplace:
270 line = self.get_array_name(var)
271 if index_var in self.iterate_all:
272 line = f"{line}[:]"
273 else:
274 line = f"{line}[{index_var}]"
275 line = f"{line} = {varname}"
276 lines.append(line)
277 return lines
278
279 def conditional_write(
280 self, line, stmt, variables, conditional_write_vars, created_vars
281 ):
282 if stmt.var in conditional_write_vars:
283 subs = {}
284 index = conditional_write_vars[stmt.var]
285 # we replace all var with var[index], but actually we use this repl_string first because
286 # we don't want to end up with lines like x[not_refractory[not_refractory]] when
287 # multiple substitution passes are invoked
288 repl_string = ( # this string shouldn't occur anywhere I hope! :)
289 "#$(@#&$@$*U#@)$@(#"
290 )
291 for varname, var in list(variables.items()):
292 if isinstance(var, ArrayVariable) and not var.scalar:
293 subs[varname] = f"{varname}[{repl_string}]"
294 # all newly created vars are arrays and will need indexing
295 for varname in created_vars:
296 subs[varname] = f"{varname}[{repl_string}]"
297 # Also index _vectorisation_idx so that e.g. rand() works correctly
298 subs["_vectorisation_idx"] = f"_vectorisation_idx[{repl_string}]"
299
300 line = word_substitute(line, subs)
301 line = line.replace(repl_string, index)
302 return line
303
304 def translate_one_statement_sequence(self, statements, scalar=False):
305 variables = self.variables
306 variable_indices = self.variable_indices
307 read, write, indices, conditional_write_vars = self.arrays_helper(statements)
308 lines = []
309
310 all_unique = not self.has_repeated_indices(statements)
311
312 if scalar or all_unique:
313 # Simple translation
314 lines.extend(
315 self.read_arrays(read, write, indices, variables, variable_indices)
316 )
317 created_vars = {stmt.var for stmt in statements if stmt.op == ":="}
318 for stmt in statements:
319 line = self.translate_statement(stmt)
320 line = self.conditional_write(
321 line, stmt, variables, conditional_write_vars, created_vars
322 )
323 lines.append(line)
324 lines.extend(
325 self.write_arrays(statements, read, write, variables, variable_indices)
326 )
327 else:
328 # More complex translation to deal with repeated indices
329 lines.extend(self.vectorise_code(statements, variables, variable_indices))
330
331 return lines
332
333
334 ################################################################################
335 # Implement functions
336 ################################################################################
337 # Functions that exist under the same name in numpy
338 for func_name, func in [
339 ("sin", np.sin),
340 ("cos", np.cos),
341 ("tan", np.tan),
342 ("sinh", np.sinh),
343 ("cosh", np.cosh),
344 ("tanh", np.tanh),
345 ("exp", np.exp),
346 ("log", np.log),
347 ("log10", np.log10),
348 ("sqrt", np.sqrt),
349 ("arcsin", np.arcsin),
350 ("arccos", np.arccos),
351 ("arctan", np.arctan),
352 ("abs", np.abs),
353 ("sign", np.sign),
354 ]:
355 DEFAULT_FUNCTIONS[func_name].implementations.add_implementation(
356 NumpyCodeGenerator, code=func
357 )
358
359
360 # Functions that are implemented in a somewhat special way
361 def randn_func(vectorisation_idx):
362 try:
363 N = len(vectorisation_idx)
364 return np.random.randn(N)
365 except TypeError:
366 # scalar value
367 return np.random.randn()
368
369
370 def rand_func(vectorisation_idx):
371 try:
372 N = len(vectorisation_idx)
373 return np.random.rand(N)
374 except TypeError:
375 # scalar value
376 return np.random.rand()
377
378
379 def poisson_func(lam, vectorisation_idx):
380 try:
381 N = len(vectorisation_idx)
382 return np.random.poisson(lam, size=N)
383 except TypeError:
384 # scalar value
385 return np.random.poisson(lam)
386
387
388 DEFAULT_FUNCTIONS["randn"].implementations.add_implementation(
389 NumpyCodeGenerator, code=randn_func
390 )
391 DEFAULT_FUNCTIONS["rand"].implementations.add_implementation(
392 NumpyCodeGenerator, code=rand_func
393 )
394 DEFAULT_FUNCTIONS["poisson"].implementations.add_implementation(
395 NumpyCodeGenerator, code=poisson_func
396 )
397 clip_func = lambda array, a_min, a_max: np.clip(array, a_min, a_max)
398 DEFAULT_FUNCTIONS["clip"].implementations.add_implementation(
399 NumpyCodeGenerator, code=clip_func
400 )
401 int_func = lambda value: np.int32(value)
402 DEFAULT_FUNCTIONS["int"].implementations.add_implementation(
403 NumpyCodeGenerator, code=int_func
404 )
405 ceil_func = lambda value: np.int32(np.ceil(value))
406 DEFAULT_FUNCTIONS["ceil"].implementations.add_implementation(
407 NumpyCodeGenerator, code=ceil_func
408 )
409 floor_func = lambda value: np.int32(np.floor(value))
410 DEFAULT_FUNCTIONS["floor"].implementations.add_implementation(
411 NumpyCodeGenerator, code=floor_func
412 )
413
414 # We need to explicitly add an implementation for the timestep function,
415 # otherwise Brian would *add* units during simulation, thinking that the
416 # timestep function would not work correctly otherwise. This would slow the
417 # function down significantly.
418 DEFAULT_FUNCTIONS["timestep"].implementations.add_implementation(
419 NumpyCodeGenerator, code=timestep
420 )