| 1 |
""" |
| 2 |
Module containing the `Device` base class as well as the `RuntimeDevice` |
| 3 |
implementation and some helper functions to access/set devices. |
| 4 |
""" |
| 5 |
|
| 6 |
import numbers |
| 7 |
from weakref import WeakKeyDictionary |
| 8 |
|
| 9 |
import numpy as np |
| 10 |
|
| 11 |
from brian2.codegen.targets import codegen_targets |
| 12 |
from brian2.core.names import find_name |
| 13 |
from brian2.core.preferences import prefs |
| 14 |
from brian2.core.variables import ArrayVariable, DynamicArrayVariable |
| 15 |
from brian2.memory.dynamicarray import DynamicArray, DynamicArray1D |
| 16 |
from brian2.units import ms |
| 17 |
from brian2.utils.logger import get_logger |
| 18 |
from brian2.utils.stringtools import code_representation, indent |
| 19 |
|
| 20 |
__all__ = [ |
| 21 |
"Device", |
| 22 |
"RuntimeDevice", |
| 23 |
"get_device", |
| 24 |
"set_device", |
| 25 |
"all_devices", |
| 26 |
"reinit_devices", |
| 27 |
"reinit_and_delete", |
| 28 |
"reset_device", |
| 29 |
"device", |
| 30 |
"seed", |
| 31 |
] |
| 32 |
|
| 33 |
logger = get_logger(__name__) |
| 34 |
|
| 35 |
all_devices = {} |
| 36 |
|
| 37 |
|
| 38 |
prefs.register_preferences("devices", "Device preferences") |
| 39 |
|
| 40 |
|
| 41 |
#: caches the automatically determined code generation target |
| 42 |
_auto_target = None |
| 43 |
|
| 44 |
|
| 45 |
def auto_target(): |
| 46 |
""" |
| 47 |
Automatically chose a code generation target (invoked when the |
| 48 |
`codegen.target` preference is set to `'auto'`. Caches its result so it |
| 49 |
only does the check once. Prefers cython > numpy. |
| 50 |
|
| 51 |
Returns |
| 52 |
------- |
| 53 |
target : class derived from `CodeObject` |
| 54 |
The target to use |
| 55 |
""" |
| 56 |
global _auto_target |
| 57 |
if _auto_target is None: |
| 58 |
target_dict = { |
| 59 |
target.class_name: target for target in codegen_targets if target.class_name |
| 60 |
} |
| 61 |
using_fallback = False |
| 62 |
if "cython" in target_dict and target_dict["cython"].is_available(): |
| 63 |
_auto_target = target_dict["cython"] |
| 64 |
else: |
| 65 |
_auto_target = target_dict["numpy"] |
| 66 |
using_fallback = True |
| 67 |
|
| 68 |
if using_fallback: |
| 69 |
logger.info( |
| 70 |
"Cannot use compiled code, falling back to the numpy " |
| 71 |
"code generation target. Note that this will likely " |
| 72 |
"be slower than using compiled code. Set the code " |
| 73 |
"generation to numpy manually to avoid this message:\n" |
| 74 |
'prefs.codegen.target = "numpy"', |
| 75 |
"codegen_fallback", |
| 76 |
once=True, |
| 77 |
) |
| 78 |
else: |
| 79 |
logger.debug( |
| 80 |
"Chosing %r as the code generation target." % _auto_target.class_name |
| 81 |
) |
| 82 |
|
| 83 |
return _auto_target |
| 84 |
|
| 85 |
|
| 86 |
class Device: |
| 87 |
""" |
| 88 |
Base Device object. |
| 89 |
""" |
| 90 |
|
| 91 |
def __init__(self): |
| 92 |
#: The network schedule that this device supports. If the device only |
| 93 |
#: supports a specific, fixed schedule, it has to set this attribute to |
| 94 |
#: the respective schedule (see `Network.schedule` for details). If it |
| 95 |
#: supports arbitrary schedules, it should be set to ``None`` (the |
| 96 |
#: default). |
| 97 |
self.network_schedule = None |
| 98 |
|
| 99 |
self.defaultclock = None |
| 100 |
|
| 101 |
self._maximum_run_time = None |
| 102 |
|
| 103 |
self._state_tuple = (self.__module__, self.__class__.__name__) |
| 104 |
|
| 105 |
def _set_maximum_run_time(self, maximum_run_time): |
| 106 |
""" |
| 107 |
Sets a maximum time for a run before it will break. Used primarily for testing purposes. Not guaranteed to be |
| 108 |
respected by a device. |
| 109 |
""" |
| 110 |
self._maximum_run_time = maximum_run_time |
| 111 |
|
| 112 |
def get_array_name(self, var, access_data=True): |
| 113 |
""" |
| 114 |
Return a globally unique name for `var`. |
| 115 |
|
| 116 |
Parameters |
| 117 |
---------- |
| 118 |
access_data : bool, optional |
| 119 |
For `DynamicArrayVariable` objects, specifying `True` here means the |
| 120 |
name for the underlying data is returned. If specifying `False`, |
| 121 |
the name of object itself is returned (e.g. to allow resizing). |
| 122 |
|
| 123 |
Returns |
| 124 |
------- |
| 125 |
name : str |
| 126 |
The name for `var`. |
| 127 |
""" |
| 128 |
raise NotImplementedError() |
| 129 |
|
| 130 |
def get_len(self, array): |
| 131 |
""" |
| 132 |
Return the length of the array. |
| 133 |
|
| 134 |
Parameters |
| 135 |
---------- |
| 136 |
array : `ArrayVariable` |
| 137 |
The array for which the length is requested. |
| 138 |
|
| 139 |
Returns |
| 140 |
------- |
| 141 |
l : int |
| 142 |
The length of the array. |
| 143 |
""" |
| 144 |
raise NotImplementedError() |
| 145 |
|
| 146 |
def add_array(self, var): |
| 147 |
""" |
| 148 |
Add an array to this device. |
| 149 |
|
| 150 |
Parameters |
| 151 |
---------- |
| 152 |
var : `ArrayVariable` |
| 153 |
The array to add. |
| 154 |
""" |
| 155 |
raise NotImplementedError() |
| 156 |
|
| 157 |
def init_with_zeros(self, var, dtype): |
| 158 |
""" |
| 159 |
Initialize an array with zeros. |
| 160 |
|
| 161 |
Parameters |
| 162 |
---------- |
| 163 |
var : `ArrayVariable` |
| 164 |
The array to initialize with zeros. |
| 165 |
dtype : `dtype` |
| 166 |
The data type to use for the array. |
| 167 |
""" |
| 168 |
raise NotImplementedError() |
| 169 |
|
| 170 |
def init_with_arange(self, var, start, dtype): |
| 171 |
""" |
| 172 |
Initialize an array with an integer range. |
| 173 |
|
| 174 |
Parameters |
| 175 |
---------- |
| 176 |
var : `ArrayVariable` |
| 177 |
The array to fill with the integer range. |
| 178 |
start : int |
| 179 |
The start value for the integer range |
| 180 |
dtype : `dtype` |
| 181 |
The data type to use for the array. |
| 182 |
""" |
| 183 |
raise NotImplementedError() |
| 184 |
|
| 185 |
def fill_with_array(self, var, arr): |
| 186 |
""" |
| 187 |
Fill an array with the values given in another array. |
| 188 |
|
| 189 |
Parameters |
| 190 |
---------- |
| 191 |
var : `ArrayVariable` |
| 192 |
The array to fill. |
| 193 |
arr : `ndarray` |
| 194 |
The array values that should be copied to `var`. |
| 195 |
""" |
| 196 |
raise NotImplementedError() |
| 197 |
|
| 198 |
def spike_queue(self, source_start, source_end): |
| 199 |
""" |
| 200 |
Create and return a new `SpikeQueue` for this `Device`. |
| 201 |
|
| 202 |
Parameters |
| 203 |
---------- |
| 204 |
source_start : int |
| 205 |
The start index of the source group (necessary for subgroups) |
| 206 |
source_end : int |
| 207 |
The end index of the source group (necessary for subgroups) |
| 208 |
""" |
| 209 |
raise NotImplementedError() |
| 210 |
|
| 211 |
def resize(self, var, new_size): |
| 212 |
""" |
| 213 |
Resize a `DynamicArrayVariable`. |
| 214 |
|
| 215 |
Parameters |
| 216 |
---------- |
| 217 |
var : `DynamicArrayVariable` |
| 218 |
The variable that should be resized. |
| 219 |
new_size : int |
| 220 |
The new size of the variable |
| 221 |
""" |
| 222 |
raise NotImplementedError() |
| 223 |
|
| 224 |
def resize_along_first(self, var, new_size): |
| 225 |
# Can be overwritten with a better implementation |
| 226 |
return self.resize(var, new_size) |
| 227 |
|
| 228 |
def seed(self, seed=None): |
| 229 |
""" |
| 230 |
Set the seed for the random number generator. |
| 231 |
|
| 232 |
Parameters |
| 233 |
---------- |
| 234 |
seed : int, optional |
| 235 |
The seed value for the random number generator, or ``None`` (the |
| 236 |
default) to set a random seed. |
| 237 |
""" |
| 238 |
raise NotImplementedError() |
| 239 |
|
| 240 |
def code_object_class(self, codeobj_class=None, fallback_pref="codegen.target"): |
| 241 |
""" |
| 242 |
Return `CodeObject` class according to input/default settings |
| 243 |
|
| 244 |
Parameters |
| 245 |
---------- |
| 246 |
codeobj_class : a `CodeObject` class, optional |
| 247 |
If this is keyword is set to None or no arguments are given, this method will return |
| 248 |
the default. |
| 249 |
fallback_pref : str, optional |
| 250 |
String describing which attribute of prefs to access to retrieve the 'default' target. |
| 251 |
Usually this is codegen.target, but in some cases we want to use object-specific targets |
| 252 |
such as codegen.string_expression_target. |
| 253 |
|
| 254 |
Returns |
| 255 |
------- |
| 256 |
codeobj_class : class |
| 257 |
The `CodeObject` class that should be used |
| 258 |
""" |
| 259 |
if isinstance(codeobj_class, str): |
| 260 |
raise TypeError( |
| 261 |
"codeobj_class argument given to code_object_class device method " |
| 262 |
"should be a CodeObject class, not a string. You can, however, " |
| 263 |
"send a string description of the target desired for the CodeObject " |
| 264 |
"under the keyword fallback_pref" |
| 265 |
) |
| 266 |
if codeobj_class is None: |
| 267 |
codeobj_class = prefs[fallback_pref] |
| 268 |
if isinstance(codeobj_class, str): |
| 269 |
if codeobj_class == "auto": |
| 270 |
return auto_target() |
| 271 |
for target in codegen_targets: |
| 272 |
if target.class_name == codeobj_class: |
| 273 |
return target |
| 274 |
# No target found |
| 275 |
targets = ["auto"] + [ |
| 276 |
target.class_name for target in codegen_targets if target.class_name |
| 277 |
] |
| 278 |
raise ValueError( |
| 279 |
f"Unknown code generation target: {codeobj_class}, should be one" |
| 280 |
f" of {targets}" |
| 281 |
) |
| 282 |
else: |
| 283 |
return codeobj_class |
| 284 |
|
| 285 |
def code_object( |
| 286 |
self, |
| 287 |
owner, |
| 288 |
name, |
| 289 |
abstract_code, |
| 290 |
variables, |
| 291 |
template_name, |
| 292 |
variable_indices, |
| 293 |
codeobj_class=None, |
| 294 |
template_kwds=None, |
| 295 |
override_conditional_write=None, |
| 296 |
compiler_kwds=None, |
| 297 |
): |
| 298 |
if compiler_kwds is None: |
| 299 |
compiler_kwds = {} |
| 300 |
name = find_name(name) |
| 301 |
codeobj_class = self.code_object_class(codeobj_class) |
| 302 |
template = getattr(codeobj_class.templater, template_name) |
| 303 |
iterate_all = template.iterate_all |
| 304 |
generator = codeobj_class.generator_class( |
| 305 |
variables=variables, |
| 306 |
variable_indices=variable_indices, |
| 307 |
owner=owner, |
| 308 |
iterate_all=iterate_all, |
| 309 |
codeobj_class=codeobj_class, |
| 310 |
override_conditional_write=override_conditional_write, |
| 311 |
allows_scalar_write=template.allows_scalar_write, |
| 312 |
name=name, |
| 313 |
template_name=template_name, |
| 314 |
) |
| 315 |
if template_kwds is None: |
| 316 |
template_kwds = dict() |
| 317 |
else: |
| 318 |
template_kwds = template_kwds.copy() |
| 319 |
|
| 320 |
logger.diagnostic( |
| 321 |
f"{name} abstract code:\n{indent(code_representation(abstract_code))}" |
| 322 |
) |
| 323 |
|
| 324 |
scalar_code, vector_code, kwds = generator.translate( |
| 325 |
abstract_code, dtype=prefs["core.default_float_dtype"] |
| 326 |
) |
| 327 |
|
| 328 |
# Add the array names as keywords as well |
| 329 |
for varname, var in variables.items(): |
| 330 |
if isinstance(var, ArrayVariable): |
| 331 |
pointer_name = generator.get_array_name(var) |
| 332 |
if var.scalar: |
| 333 |
pointer_name += "[0]" |
| 334 |
template_kwds[varname] = pointer_name |
| 335 |
if hasattr(var, "resize"): |
| 336 |
dyn_array_name = generator.get_array_name(var, access_data=False) |
| 337 |
template_kwds[f"_dynamic_{varname}"] = dyn_array_name |
| 338 |
template_kwds[f"_dynamic_{varname}_ptr"] = ( |
| 339 |
f"{dyn_array_name}_ptr" # so we can access the right name of dynamic array pointer |
| 340 |
) |
| 341 |
|
| 342 |
template_kwds.update(kwds) |
| 343 |
logger.diagnostic( |
| 344 |
f"{name} snippet (scalar):\n{indent(code_representation(scalar_code))}" |
| 345 |
) |
| 346 |
logger.diagnostic( |
| 347 |
f"{name} snippet (vector):\n{indent(code_representation(vector_code))}" |
| 348 |
) |
| 349 |
code = template( |
| 350 |
scalar_code, |
| 351 |
vector_code, |
| 352 |
owner=owner, |
| 353 |
variables=variables, |
| 354 |
codeobj_name=name, |
| 355 |
variable_indices=variable_indices, |
| 356 |
get_array_name=generator.get_array_name, |
| 357 |
**template_kwds, |
| 358 |
) |
| 359 |
logger.diagnostic(f"{name} code:\n{indent(code_representation(code))}") |
| 360 |
|
| 361 |
codeobj = codeobj_class( |
| 362 |
owner, |
| 363 |
code, |
| 364 |
variables, |
| 365 |
variable_indices, |
| 366 |
template_name=template_name, |
| 367 |
template_source=template.template_source, |
| 368 |
name=name, |
| 369 |
compiler_kwds=compiler_kwds, |
| 370 |
) |
| 371 |
codeobj.compile() |
| 372 |
return codeobj |
| 373 |
|
| 374 |
def activate(self, build_on_run=True, **kwargs): |
| 375 |
""" |
| 376 |
Called when this device is set as the current device. |
| 377 |
""" |
| 378 |
from brian2.core.clocks import Clock # avoid import issues |
| 379 |
|
| 380 |
if self.defaultclock is None: |
| 381 |
self.defaultclock = Clock(dt=0.1 * ms, name="defaultclock") |
| 382 |
self._set_maximum_run_time(None) |
| 383 |
self.build_on_run = build_on_run |
| 384 |
self.build_options = dict(kwargs) |
| 385 |
|
| 386 |
def insert_device_code(self, slot, code): |
| 387 |
# Deprecated |
| 388 |
raise AttributeError( |
| 389 |
"The method 'insert_device_code' has been renamed to 'insert_code'." |
| 390 |
) |
| 391 |
|
| 392 |
def insert_code(self, slot, code): |
| 393 |
""" |
| 394 |
Insert code directly into a given slot in the device. By default does nothing. |
| 395 |
""" |
| 396 |
logger.warn(f"Ignoring device code, unknown slot: {slot}, code: {code}") |
| 397 |
|
| 398 |
def build(self, **kwds): |
| 399 |
""" |
| 400 |
For standalone projects, called when the project is ready to be built. Does nothing for runtime mode. |
| 401 |
""" |
| 402 |
pass |
| 403 |
|
| 404 |
def reinit(self): |
| 405 |
""" |
| 406 |
Reinitialize the device. For standalone devices, clears all the internal |
| 407 |
state of the device. |
| 408 |
""" |
| 409 |
pass |
| 410 |
|
| 411 |
def delete(self, data=True, code=True, directory=True, force=False): |
| 412 |
""" |
| 413 |
Delete code and/or data generated/stored by the device. |
| 414 |
|
| 415 |
Parameters |
| 416 |
---------- |
| 417 |
data : bool, optional |
| 418 |
Whether to delete the data generated by the simulation (final values |
| 419 |
of state variables, data stored in monitors, etc.). Defaults to |
| 420 |
``True``. |
| 421 |
code : bool, optional |
| 422 |
Whether to delete the code generated by the simulation. Includes the |
| 423 |
numerical values used for initialization of state variables in |
| 424 |
assignments not using strings. Defaults to ``True``. |
| 425 |
directory : bool, optional |
| 426 |
Whether to delete the project directory generated by the simulation. |
| 427 |
Will not delete directories that contain files not created by Brian |
| 428 |
unless the ``force`` option is specfied. Defaults to ``True``. |
| 429 |
force : bool, optional |
| 430 |
Whether to delete the project directory with all its content, even |
| 431 |
if it contains files that were not created by Brian. Useful only |
| 432 |
when the ``directory`` option is set to ``True`` as well. Defaults |
| 433 |
to ``False``. |
| 434 |
""" |
| 435 |
pass |
| 436 |
|
| 437 |
def get_random_state(self): |
| 438 |
""" |
| 439 |
Return a (pickable) representation of the current random number |
| 440 |
generator state. Providing the returned object (e.g. a dict) to |
| 441 |
`.Device.set_random_state` should restore the random number generator |
| 442 |
state. |
| 443 |
|
| 444 |
Returns |
| 445 |
------- |
| 446 |
state |
| 447 |
The state of the random number generator in a representation |
| 448 |
that can be passed as an argument to `.Device.set_random_state`. |
| 449 |
""" |
| 450 |
raise NotImplementedError( |
| 451 |
"Device does not support getting the state of the random number generator." |
| 452 |
) |
| 453 |
|
| 454 |
def set_random_state(self, state): |
| 455 |
""" |
| 456 |
Reset the random number generator state to a previously stored state |
| 457 |
(see `.Device.get_random_state`). |
| 458 |
|
| 459 |
Parameters |
| 460 |
---------- |
| 461 |
state |
| 462 |
A random number generator state as provided by |
| 463 |
`Device.get_random_state`. |
| 464 |
""" |
| 465 |
raise NotImplementedError( |
| 466 |
"Device does not support setting the state of the random number generator." |
| 467 |
) |
| 468 |
|
| 469 |
|
| 470 |
class RuntimeDevice(Device): |
| 471 |
""" |
| 472 |
The default device used in Brian, state variables are stored as numpy |
| 473 |
arrays in memory. |
| 474 |
""" |
| 475 |
|
| 476 |
def __init__(self): |
| 477 |
super().__init__() |
| 478 |
#: Mapping from `Variable` objects to numpy arrays (or `DynamicArray` |
| 479 |
#: objects). Arrays in this dictionary will disappear as soon as the |
| 480 |
#: last reference to the `Variable` object used as a key is gone |
| 481 |
self.arrays = WeakKeyDictionary() |
| 482 |
# Note that the buffers only store a pointer to the actual random |
| 483 |
# numbers -- the buffer will be filled in Cython code |
| 484 |
self.randn_buffer = np.zeros(1, dtype=np.intp) |
| 485 |
self.rand_buffer = np.zeros(1, dtype=np.intp) |
| 486 |
self.randn_buffer_index = np.zeros(1, dtype=np.int32) |
| 487 |
self.rand_buffer_index = np.zeros(1, dtype=np.int32) |
| 488 |
|
| 489 |
def __getstate__(self): |
| 490 |
state = dict(self.__dict__) |
| 491 |
# Python's pickle module cannot pickle a WeakKeyDictionary, we therefore |
| 492 |
# convert it to a standard dictionary |
| 493 |
state["arrays"] = dict(self.arrays) |
| 494 |
return state |
| 495 |
|
| 496 |
def __setstate__(self, state): |
| 497 |
self.__dict__ = state |
| 498 |
self.__dict__["arrays"] = WeakKeyDictionary(self.__dict__["arrays"]) |
| 499 |
|
| 500 |
def get_array_name(self, var, access_data=True): |
| 501 |
# if no owner is set, this is a temporary object (e.g. the array |
| 502 |
# of indices when doing G.x[indices] = ...). The name is not |
| 503 |
# necessarily unique over several CodeObjects in this case. |
| 504 |
owner_name = getattr(var.owner, "name", "temporary") |
| 505 |
|
| 506 |
if isinstance(var, DynamicArrayVariable): |
| 507 |
if access_data: |
| 508 |
return f"_array_{owner_name}_{var.name}" |
| 509 |
else: |
| 510 |
return f"_dynamic_array_{owner_name}_{var.name}" |
| 511 |
|
| 512 |
elif isinstance(var, ArrayVariable): |
| 513 |
return f"_array_{owner_name}_{var.name}" |
| 514 |
else: |
| 515 |
raise TypeError(f"Do not have a name for variable of type {type(var)}.") |
| 516 |
|
| 517 |
def add_array(self, var): |
| 518 |
# This creates the actual numpy arrays (or DynamicArrayVariable objects) |
| 519 |
if isinstance(var, DynamicArrayVariable): |
| 520 |
if var.ndim == 1: |
| 521 |
arr = DynamicArray1D(var.size, dtype=var.dtype) |
| 522 |
else: |
| 523 |
arr = DynamicArray(var.size, dtype=var.dtype) |
| 524 |
else: |
| 525 |
arr = np.empty(var.size, dtype=var.dtype) |
| 526 |
|
| 527 |
self.arrays[var] = arr |
| 528 |
|
| 529 |
def get_value(self, var, access_data=True): |
| 530 |
if isinstance(var, DynamicArrayVariable) and access_data: |
| 531 |
return self.arrays[var].data |
| 532 |
else: |
| 533 |
return self.arrays[var] |
| 534 |
|
| 535 |
def get_capsule(self, var): |
| 536 |
""" |
| 537 |
Get a PyCapsule object for direct C++ pointer access to dynamic arrays. |
| 538 |
|
| 539 |
Parameters |
| 540 |
---------- |
| 541 |
var : DynamicArrayVariable |
| 542 |
The dynamic array variable to get the capsule for. |
| 543 |
|
| 544 |
Returns |
| 545 |
------- |
| 546 |
capsule : PyCapsule |
| 547 |
A PyCapsule containing the C++ pointer to the dynamic array. |
| 548 |
""" |
| 549 |
if not isinstance(var, DynamicArrayVariable): |
| 550 |
raise TypeError( |
| 551 |
f"get_capsule only supports DynamicArrayVariable, got {type(var)}" |
| 552 |
) |
| 553 |
|
| 554 |
array_obj = self.arrays[var] |
| 555 |
return array_obj.get_capsule() |
| 556 |
|
| 557 |
def set_value(self, var, value): |
| 558 |
self.arrays[var][:] = value |
| 559 |
|
| 560 |
def resize(self, var, new_size): |
| 561 |
self.arrays[var].resize(new_size) |
| 562 |
|
| 563 |
def resize_along_first(self, var, new_size): |
| 564 |
self.arrays[var].resize_along_first(new_size) |
| 565 |
|
| 566 |
def init_with_zeros(self, var, dtype): |
| 567 |
self.arrays[var][:] = 0 |
| 568 |
|
| 569 |
def init_with_arange(self, var, start, dtype): |
| 570 |
self.arrays[var][:] = np.arange(start, stop=var.get_len() + start, dtype=dtype) |
| 571 |
|
| 572 |
def fill_with_array(self, var, arr): |
| 573 |
self.arrays[var][:] = arr |
| 574 |
|
| 575 |
def spike_queue(self, source_start, source_end): |
| 576 |
try: |
| 577 |
from brian2.synapses.cythonspikequeue import SpikeQueue |
| 578 |
|
| 579 |
logger.diagnostic("Using the C++ SpikeQueue", once=True) |
| 580 |
return SpikeQueue(source_start=source_start, source_end=source_end) |
| 581 |
except ImportError as e: |
| 582 |
raise ImportError( |
| 583 |
"The C++/Cython SpikeQueue is required but not available. " |
| 584 |
"Please ensure Cython is installed and the extension was built properly." |
| 585 |
) from e |
| 586 |
|
| 587 |
def seed(self, seed=None): |
| 588 |
""" |
| 589 |
Set the seed for the random number generator. |
| 590 |
|
| 591 |
Parameters |
| 592 |
---------- |
| 593 |
seed : int, optional |
| 594 |
The seed value for the random number generator, or ``None`` (the |
| 595 |
default) to set a random seed. |
| 596 |
""" |
| 597 |
np.random.seed(seed) |
| 598 |
self.rand_buffer_index[:] = 0 |
| 599 |
self.randn_buffer_index[:] = 0 |
| 600 |
|
| 601 |
def get_random_state(self): |
| 602 |
return { |
| 603 |
"numpy_state": np.random.get_state(), |
| 604 |
"rand_buffer_index": np.array(self.rand_buffer_index), |
| 605 |
"rand_buffer": np.array(self.rand_buffer), |
| 606 |
"randn_buffer_index": np.array(self.randn_buffer_index), |
| 607 |
"randn_buffer": np.array(self.randn_buffer), |
| 608 |
} |
| 609 |
|
| 610 |
def set_random_state(self, state): |
| 611 |
np.random.set_state(state["numpy_state"]) |
| 612 |
self.rand_buffer_index[:] = state["rand_buffer_index"] |
| 613 |
self.rand_buffer[:] = state["rand_buffer"] |
| 614 |
self.randn_buffer_index[:] = state["randn_buffer_index"] |
| 615 |
self.randn_buffer[:] = state["randn_buffer"] |
| 616 |
|
| 617 |
|
| 618 |
class Dummy: |
| 619 |
""" |
| 620 |
Dummy object |
| 621 |
""" |
| 622 |
|
| 623 |
def __getattr__(self, name): |
| 624 |
return Dummy() |
| 625 |
|
| 626 |
def __call__(self, *args, **kwds): |
| 627 |
return Dummy() |
| 628 |
|
| 629 |
def __enter__(self): |
| 630 |
return Dummy() |
| 631 |
|
| 632 |
def __exit__(self, type, value, traceback): |
| 633 |
pass |
| 634 |
|
| 635 |
def __getitem__(self, i): |
| 636 |
return Dummy() |
| 637 |
|
| 638 |
def __setitem__(self, i, val): |
| 639 |
pass |
| 640 |
|
| 641 |
|
| 642 |
class CurrentDeviceProxy: |
| 643 |
""" |
| 644 |
Method proxy for access to the currently active device |
| 645 |
""" |
| 646 |
|
| 647 |
def __getattr__(self, name): |
| 648 |
if not hasattr(active_device, name): |
| 649 |
# We special case the name "shape" here, since some IDEs (e.g. The Python |
| 650 |
# console in PyDev and PyCharm) use the "shape" attribute to determine |
| 651 |
# whether an object is "array-like". |
| 652 |
if name.startswith("_") or name == "shape": |
| 653 |
# Do not fake private/magic attributes |
| 654 |
raise AttributeError( |
| 655 |
f"Active device does not have an attribute '{name}'." |
| 656 |
) |
| 657 |
else: |
| 658 |
logger.warn( |
| 659 |
f"Active device does not have an attribute '{name}', ignoring this." |
| 660 |
) |
| 661 |
attr = Dummy() |
| 662 |
else: |
| 663 |
attr = getattr(active_device, name) |
| 664 |
return attr |
| 665 |
|
| 666 |
|
| 667 |
#: Proxy object to access methods of the current device |
| 668 |
device = CurrentDeviceProxy() |
| 669 |
#: The currently active device (set with `set_device`) |
| 670 |
active_device = None |
| 671 |
|
| 672 |
|
| 673 |
def get_device(): |
| 674 |
""" |
| 675 |
Gets the actve `Device` object |
| 676 |
""" |
| 677 |
global active_device |
| 678 |
return active_device |
| 679 |
|
| 680 |
|
| 681 |
#: A stack of previously set devices as a tuple with their options (see |
| 682 |
#: `set_device`): (device, build_on_run, build_options) |
| 683 |
previous_devices = [] |
| 684 |
|
| 685 |
|
| 686 |
def set_device(device, build_on_run=True, **kwargs): |
| 687 |
""" |
| 688 |
Set the device used for simulations. |
| 689 |
|
| 690 |
Parameters |
| 691 |
---------- |
| 692 |
device : `Device` or str |
| 693 |
The `Device` object or the name of the device. |
| 694 |
build_on_run : bool, optional |
| 695 |
Whether a call to `run` (or `Network.run`) should directly trigger a |
| 696 |
`Device.build`. This is only relevant for standalone devices and means |
| 697 |
that a run call directly triggers the start of a simulation. If the |
| 698 |
simulation consists of multiple run calls, set ``build_on_run`` to |
| 699 |
``False`` and call `Device.build` explicitly. Defaults to ``True``. |
| 700 |
kwargs : dict, optional |
| 701 |
Only relevant when ``build_on_run`` is ``True``: additional arguments |
| 702 |
that will be given to the `Device.build` call. |
| 703 |
""" |
| 704 |
global previous_devices |
| 705 |
if active_device is not None: |
| 706 |
prev_build_on_run = getattr(active_device, "build_on_run", True) |
| 707 |
prev_build_options = getattr(active_device, "build_options", {}) |
| 708 |
previous_devices.append((active_device, prev_build_on_run, prev_build_options)) |
| 709 |
_do_set_device(device, build_on_run, **kwargs) |
| 710 |
|
| 711 |
|
| 712 |
def _do_set_device(device, build_on_run=True, **kwargs): |
| 713 |
global active_device |
| 714 |
|
| 715 |
if isinstance(device, str): |
| 716 |
device = all_devices[device] |
| 717 |
if active_device is not None and active_device.defaultclock is not None: |
| 718 |
previous_dt = active_device.defaultclock.dt |
| 719 |
else: |
| 720 |
previous_dt = None |
| 721 |
active_device = device |
| 722 |
|
| 723 |
active_device.activate(build_on_run=build_on_run, **kwargs) |
| 724 |
if previous_dt is not None: |
| 725 |
# Copy over the dt information of the defaultclock |
| 726 |
active_device.defaultclock.dt = previous_dt |
| 727 |
|
| 728 |
|
| 729 |
def reset_device(device=None): |
| 730 |
""" |
| 731 |
Reset to a previously used device. Restores also the previously specified |
| 732 |
build options (see `set_device`) for the device. Mostly useful for internal |
| 733 |
Brian code and testing on various devices. |
| 734 |
|
| 735 |
Parameters |
| 736 |
---------- |
| 737 |
device : `Device` or str, optional |
| 738 |
The device to go back to. If none is specified, go back to the device |
| 739 |
chosen with `set_device` before the current one. |
| 740 |
""" |
| 741 |
global previous_devices |
| 742 |
if isinstance(device, str): |
| 743 |
device = all_devices[device] |
| 744 |
|
| 745 |
if len(previous_devices) == 0 and device is None: |
| 746 |
device = runtime_device |
| 747 |
build_on_run = True |
| 748 |
build_options = {} |
| 749 |
elif device is None: |
| 750 |
device, build_on_run, build_options = previous_devices.pop() |
| 751 |
else: |
| 752 |
build_on_run = device.build_on_run |
| 753 |
build_options = device.build_options |
| 754 |
|
| 755 |
_do_set_device(device, build_on_run, **build_options) |
| 756 |
|
| 757 |
|
| 758 |
def reinit_devices(): |
| 759 |
""" |
| 760 |
Reinitialize all devices, call `Device.activate` again on the current |
| 761 |
device and reset the preferences. Used as a "teardown" function in testing, |
| 762 |
if users want to reset their device (e.g. for multiple standalone runs in a |
| 763 |
single script), calling ``device.reinit()`` followed by |
| 764 |
``device.activate()`` should normally be sufficient. |
| 765 |
|
| 766 |
Notes |
| 767 |
----- |
| 768 |
This also resets the `defaultclock`, i.e. a non-standard ``dt`` has to be |
| 769 |
set again. |
| 770 |
""" |
| 771 |
from brian2 import restore_initial_state # avoids circular import |
| 772 |
|
| 773 |
for device in all_devices.values(): |
| 774 |
device.reinit() |
| 775 |
|
| 776 |
if active_device is not None: |
| 777 |
# Reactivate the current device |
| 778 |
reset_device(active_device) |
| 779 |
|
| 780 |
restore_initial_state() |
| 781 |
|
| 782 |
|
| 783 |
def reinit_and_delete(): |
| 784 |
""" |
| 785 |
Calls `reinit_devices` and additionally deletes the files left behind by |
| 786 |
the standalone mode in the temporary directory. |
| 787 |
Silently suppresses errors that occur while deleting the directory. |
| 788 |
""" |
| 789 |
reinit_devices() |
| 790 |
device.delete(directory=True, force=True) |
| 791 |
|
| 792 |
|
| 793 |
def seed(seed=None): |
| 794 |
""" |
| 795 |
Set the seed for the random number generator. |
| 796 |
|
| 797 |
Parameters |
| 798 |
---------- |
| 799 |
seed : int, optional |
| 800 |
The seed value for the random number generator, or ``None`` (the |
| 801 |
default) to set a random seed. |
| 802 |
|
| 803 |
Notes |
| 804 |
----- |
| 805 |
This function delegates the call to `Device.seed` of the current device. |
| 806 |
""" |
| 807 |
if seed is not None and not isinstance(seed, numbers.Integral): |
| 808 |
raise TypeError(f"Seed has to be None or an integer, was {type(seed)}") |
| 809 |
get_device().seed(seed) |
| 810 |
|
| 811 |
|
| 812 |
runtime_device = RuntimeDevice() |
| 813 |
all_devices["runtime"] = runtime_device |