| 1 |
""" |
| 2 |
Module providing `NumpyCodeObject`. |
| 3 |
""" |
| 4 |
|
| 5 |
import sys |
| 6 |
from collections.abc import Iterable |
| 7 |
|
| 8 |
import numpy as np |
| 9 |
|
| 10 |
from brian2.core.base import BrianObjectException |
| 11 |
from brian2.core.functions import Function |
| 12 |
from brian2.core.preferences import BrianPreference, prefs |
| 13 |
from brian2.core.variables import ( |
| 14 |
ArrayVariable, |
| 15 |
AuxiliaryVariable, |
| 16 |
DynamicArrayVariable, |
| 17 |
Subexpression, |
| 18 |
) |
| 19 |
|
| 20 |
from ...codeobject import CodeObject, check_compiler_kwds, constant_or_scalar |
| 21 |
from ...generators.numpy_generator import NumpyCodeGenerator |
| 22 |
from ...targets import codegen_targets |
| 23 |
from ...templates import Templater |
| 24 |
|
| 25 |
__all__ = ["NumpyCodeObject"] |
| 26 |
|
| 27 |
# Preferences |
| 28 |
prefs.register_preferences( |
| 29 |
"codegen.runtime.numpy", |
| 30 |
"Numpy runtime codegen preferences", |
| 31 |
discard_units=BrianPreference( |
| 32 |
default=False, |
| 33 |
docs=""" |
| 34 |
Whether to change the namespace of user-specifed functions to remove |
| 35 |
units. |
| 36 |
""", |
| 37 |
), |
| 38 |
) |
| 39 |
|
| 40 |
|
| 41 |
class LazyArange(Iterable): |
| 42 |
""" |
| 43 |
A class that can be used as a `~numpy.arange` replacement (with an implied |
| 44 |
step size of 1) but does not actually create an array of values until |
| 45 |
necessary. It is somewhat similar to the ``range()`` function in Python 3, |
| 46 |
but does not use a generator. It is tailored to a special use case, the |
| 47 |
``_vectorisation_idx`` variable in numpy templates, and not meant for |
| 48 |
general use. The ``_vectorisation_idx`` is used for stateless function |
| 49 |
calls such as ``rand()`` and for the numpy codegen target determines the |
| 50 |
number of values produced by such a call. This will often be the number of |
| 51 |
neurons or synapses, and this class avoids creating a new array of that size |
| 52 |
at every code object call when all that is needed is the *length* of the |
| 53 |
array. |
| 54 |
|
| 55 |
Examples |
| 56 |
-------- |
| 57 |
>>> from brian2.codegen.runtime.numpy_rt.numpy_rt import LazyArange |
| 58 |
>>> ar = LazyArange(10) |
| 59 |
>>> len(ar) |
| 60 |
10 |
| 61 |
>>> len(ar[:5]) |
| 62 |
5 |
| 63 |
>>> type(ar[:5]) |
| 64 |
<class 'brian2.codegen.runtime.numpy_rt.numpy_rt.LazyArange'> |
| 65 |
>>> ar[5] |
| 66 |
5 |
| 67 |
>>> for value in ar[3:7]: |
| 68 |
... print(value) |
| 69 |
... |
| 70 |
3 |
| 71 |
4 |
| 72 |
5 |
| 73 |
6 |
| 74 |
>>> len(ar[np.array([1, 2, 3])]) |
| 75 |
3 |
| 76 |
""" |
| 77 |
|
| 78 |
def __init__(self, stop, start=0, indices=None): |
| 79 |
self.start = start |
| 80 |
self.stop = stop |
| 81 |
self.indices = indices |
| 82 |
|
| 83 |
def __len__(self): |
| 84 |
if self.indices is None: |
| 85 |
return self.stop - self.start |
| 86 |
else: |
| 87 |
return len(self.indices) |
| 88 |
|
| 89 |
def __getitem__(self, item): |
| 90 |
if isinstance(item, slice): |
| 91 |
if self.indices is None: |
| 92 |
start, stop, step = item.start, item.stop, item.step |
| 93 |
if step not in [None, 1]: |
| 94 |
raise NotImplementedError("Step should be 1") |
| 95 |
if start is None: |
| 96 |
start = 0 |
| 97 |
if stop is None: |
| 98 |
stop = len(self) |
| 99 |
return LazyArange( |
| 100 |
start=self.start + start, stop=min([self.start + stop, self.stop]) |
| 101 |
) |
| 102 |
else: |
| 103 |
raise NotImplementedError("Cannot slice LazyArange with indices") |
| 104 |
elif isinstance(item, np.ndarray): |
| 105 |
if item.dtype == np.dtype(bool): |
| 106 |
item = np.nonzero(item)[0] # convert boolean array into integers |
| 107 |
if len(item) == 0: |
| 108 |
return np.array([], dtype=np.int32) |
| 109 |
if np.min(item) < 0 or np.max(item) > len(self): |
| 110 |
raise IndexError("Indexing array contains out-of-bounds values") |
| 111 |
return LazyArange(start=self.start, stop=self.stop, indices=item) |
| 112 |
elif isinstance(item, int): |
| 113 |
if self.indices is None: |
| 114 |
index = self.start + item |
| 115 |
if index >= self.stop: |
| 116 |
raise IndexError(index) |
| 117 |
return index |
| 118 |
else: |
| 119 |
return self.indices[item] |
| 120 |
else: |
| 121 |
raise TypeError("Can only index with integer, numpy array, or slice.") |
| 122 |
|
| 123 |
def __iter__(self): |
| 124 |
if self.indices is None: |
| 125 |
return iter(np.arange(self.start, self.stop)) |
| 126 |
else: |
| 127 |
return iter(self.indices) |
| 128 |
|
| 129 |
# Allow conversion to a proper array with np.array(...) |
| 130 |
def __array__(self, dtype=None, copy=None): |
| 131 |
if copy is False: |
| 132 |
raise ValueError("LazyArange does not support copy=False") |
| 133 |
if self.indices is None: |
| 134 |
return np.arange(self.start, self.stop, dtype=dtype) |
| 135 |
else: |
| 136 |
return (self.indices + self.start).astype(dtype) |
| 137 |
|
| 138 |
# Allow basic arithmetics (used when shifting stuff for subgroups) |
| 139 |
def __add__(self, other): |
| 140 |
if isinstance(other, int): |
| 141 |
return LazyArange(start=self.start + other, stop=self.stop + other) |
| 142 |
else: |
| 143 |
return NotImplemented |
| 144 |
|
| 145 |
def __radd__(self, other): |
| 146 |
return self.__add__(other) |
| 147 |
|
| 148 |
def __sub__(self, other): |
| 149 |
if isinstance(other, int): |
| 150 |
return LazyArange(start=self.start - other, stop=self.stop - other) |
| 151 |
else: |
| 152 |
return NotImplemented |
| 153 |
|
| 154 |
|
| 155 |
class NumpyCodeObject(CodeObject): |
| 156 |
""" |
| 157 |
Execute code using Numpy |
| 158 |
|
| 159 |
Default for Brian because it works on all platforms. |
| 160 |
""" |
| 161 |
|
| 162 |
templater = Templater( |
| 163 |
"brian2.codegen.runtime.numpy_rt", |
| 164 |
".py_", |
| 165 |
env_globals={"constant_or_scalar": constant_or_scalar}, |
| 166 |
) |
| 167 |
generator_class = NumpyCodeGenerator |
| 168 |
class_name = "numpy" |
| 169 |
|
| 170 |
def __init__( |
| 171 |
self, |
| 172 |
owner, |
| 173 |
code, |
| 174 |
variables, |
| 175 |
variable_indices, |
| 176 |
template_name, |
| 177 |
template_source, |
| 178 |
compiler_kwds, |
| 179 |
name="numpy_code_object*", |
| 180 |
): |
| 181 |
check_compiler_kwds(compiler_kwds, [], "numpy") |
| 182 |
from brian2.devices.device import get_device |
| 183 |
|
| 184 |
self.device = get_device() |
| 185 |
self.namespace = { |
| 186 |
"_owner": owner, |
| 187 |
# TODO: This should maybe go somewhere else |
| 188 |
"logical_not": np.logical_not, |
| 189 |
} |
| 190 |
CodeObject.__init__( |
| 191 |
self, |
| 192 |
owner, |
| 193 |
code, |
| 194 |
variables, |
| 195 |
variable_indices, |
| 196 |
template_name, |
| 197 |
template_source, |
| 198 |
compiler_kwds=compiler_kwds, |
| 199 |
name=name, |
| 200 |
) |
| 201 |
self.variables_to_namespace() |
| 202 |
|
| 203 |
def variables_to_namespace(self): |
| 204 |
# Variables can refer to values that are either constant (e.g. dt) |
| 205 |
# or change every timestep (e.g. t). We add the values of the |
| 206 |
# constant variables here and add the names of non-constant variables |
| 207 |
# to a list |
| 208 |
|
| 209 |
# A list containing tuples of name and a function giving the value |
| 210 |
self.nonconstant_values = [] |
| 211 |
|
| 212 |
for name, var in self.variables.items(): |
| 213 |
if isinstance(var, (AuxiliaryVariable, Subexpression)): |
| 214 |
continue |
| 215 |
|
| 216 |
try: |
| 217 |
if not hasattr(var, "get_value"): |
| 218 |
raise TypeError() |
| 219 |
value = var.get_value() |
| 220 |
except TypeError: |
| 221 |
# Either a dummy Variable without a value or a Function object |
| 222 |
if isinstance(var, Function): |
| 223 |
impl = var.implementations[self.__class__].get_code(self.owner) |
| 224 |
self.namespace[name] = impl |
| 225 |
else: |
| 226 |
self.namespace[name] = var |
| 227 |
continue |
| 228 |
|
| 229 |
if isinstance(var, ArrayVariable): |
| 230 |
self.namespace[self.generator_class.get_array_name(var)] = value |
| 231 |
if var.scalar and var.constant: |
| 232 |
self.namespace[name] = value[0] |
| 233 |
else: |
| 234 |
self.namespace[name] = value |
| 235 |
|
| 236 |
if isinstance(var, DynamicArrayVariable): |
| 237 |
dyn_array_name = self.generator_class.get_array_name( |
| 238 |
var, access_data=False |
| 239 |
) |
| 240 |
self.namespace[dyn_array_name] = self.device.get_value( |
| 241 |
var, access_data=False |
| 242 |
) |
| 243 |
|
| 244 |
# Also provide the Variable object itself in the namespace (can be |
| 245 |
# necessary for resize operations, for example) |
| 246 |
self.namespace[f"_var_{name}"] = var |
| 247 |
|
| 248 |
# There is one type of objects that we have to inject into the |
| 249 |
# namespace with their current value at each time step: dynamic |
| 250 |
# arrays that change in size during runs (i.e. not synapses but |
| 251 |
# e.g. the structures used in monitors) |
| 252 |
if isinstance(var, DynamicArrayVariable) and var.needs_reference_update: |
| 253 |
self.nonconstant_values.append( |
| 254 |
( |
| 255 |
self.generator_class.get_array_name(var, self.variables), |
| 256 |
var.get_value, |
| 257 |
) |
| 258 |
) |
| 259 |
|
| 260 |
def update_namespace(self): |
| 261 |
# update the values of the non-constant values in the namespace |
| 262 |
for name, func in self.nonconstant_values: |
| 263 |
self.namespace[name] = func() |
| 264 |
|
| 265 |
def compile_block(self, block): |
| 266 |
code = getattr(self.code, block, "").strip() |
| 267 |
if not code or "EMPTY_CODE_BLOCK" in code: |
| 268 |
return None |
| 269 |
return compile(code, "(string)", "exec") |
| 270 |
|
| 271 |
def run_block(self, block): |
| 272 |
compiled_code = self.compiled_code[block] |
| 273 |
if not compiled_code: |
| 274 |
return |
| 275 |
try: |
| 276 |
exec(compiled_code, self.namespace) |
| 277 |
except Exception as exc: |
| 278 |
code = getattr(self.code, block) |
| 279 |
message = ( |
| 280 |
"An exception occured during the execution of the " |
| 281 |
f"'{block}' block of code object {self.name}.\n" |
| 282 |
) |
| 283 |
lines = code.split("\n") |
| 284 |
message += "The error was raised in the following line:\n" |
| 285 |
_, _, tb = sys.exc_info() |
| 286 |
tb = tb.tb_next # Line in the code object's code |
| 287 |
message += f"{lines[tb.tb_lineno - 1]}\n" |
| 288 |
raise BrianObjectException(message, self.owner) from exc |
| 289 |
# output variables should land in the variable name _return_values |
| 290 |
if "_return_values" in self.namespace: |
| 291 |
return self.namespace["_return_values"] |
| 292 |
|
| 293 |
|
| 294 |
codegen_targets.add(NumpyCodeObject) |