| 1 |
""" |
| 2 |
All Brian objects should derive from `BrianObject`. |
| 3 |
""" |
| 4 |
|
| 5 |
import functools |
| 6 |
import os |
| 7 |
import sys |
| 8 |
import traceback |
| 9 |
import weakref |
| 10 |
|
| 11 |
from brian2.core.names import Nameable |
| 12 |
from brian2.core.preferences import prefs |
| 13 |
from brian2.units.allunits import second |
| 14 |
from brian2.units.fundamentalunits import check_units |
| 15 |
from brian2.utils.logger import BrianLogger, get_logger |
| 16 |
|
| 17 |
__all__ = [ |
| 18 |
"BrianObject", |
| 19 |
"BrianObjectException", |
| 20 |
] |
| 21 |
|
| 22 |
logger = get_logger(__name__) |
| 23 |
|
| 24 |
|
| 25 |
class BrianObject(Nameable): |
| 26 |
""" |
| 27 |
All Brian objects derive from this class, defines magic tracking and update. |
| 28 |
|
| 29 |
See the documentation for `Network` for an explanation of which |
| 30 |
objects get updated in which order. |
| 31 |
|
| 32 |
Parameters |
| 33 |
---------- |
| 34 |
dt : `Quantity`, optional |
| 35 |
The time step to be used for the simulation. Cannot be combined with |
| 36 |
the `clock` argument. |
| 37 |
clock : `Clock`, optional |
| 38 |
The update clock to be used. If neither a clock, nor the `dt` argument |
| 39 |
is specified, the `defaultclock` will be used. |
| 40 |
when : str, optional |
| 41 |
In which scheduling slot to simulate the object during a time step. |
| 42 |
Defaults to ``'start'``. See :ref:`scheduling` for possible values. |
| 43 |
order : int, optional |
| 44 |
The priority of this object for operations occurring at the same time |
| 45 |
step and in the same scheduling slot. Defaults to 0. |
| 46 |
namespace: dict, optional |
| 47 |
A dictionary mapping identifier names to objects. If not given, the |
| 48 |
namespace will be filled in at the time of the call of `Network.run`, |
| 49 |
with either the values from the ``namespace`` argument of the |
| 50 |
`Network.run` method or from the local context, if no such argument is |
| 51 |
given. |
| 52 |
name : str, optional |
| 53 |
A unique name for the object - one will be assigned automatically if |
| 54 |
not provided (of the form ``brianobject_1``, etc.). |
| 55 |
Notes |
| 56 |
----- |
| 57 |
|
| 58 |
The set of all `BrianObject` objects is stored in ``BrianObject.__instances__()``. |
| 59 |
""" |
| 60 |
|
| 61 |
@check_units(dt=second) |
| 62 |
def __init__( |
| 63 |
self, |
| 64 |
dt=None, |
| 65 |
clock=None, |
| 66 |
when="start", |
| 67 |
order=0, |
| 68 |
namespace=None, |
| 69 |
name="brianobject*", |
| 70 |
): |
| 71 |
# Setup traceback information for this object |
| 72 |
creation_stack = [] |
| 73 |
bases = [] |
| 74 |
for modulename in ["brian2"]: |
| 75 |
if modulename in sys.modules: |
| 76 |
base, _ = os.path.split(sys.modules[modulename].__file__) |
| 77 |
bases.append(base) |
| 78 |
for fname, linenum, funcname, line in traceback.extract_stack(): |
| 79 |
if all(base not in fname for base in bases): |
| 80 |
s = f" File '{fname}', line {linenum}, in {funcname}\n {line}" |
| 81 |
creation_stack.append(s) |
| 82 |
creation_stack = [""] + creation_stack |
| 83 |
#: A string indicating where this object was created (traceback with any parts of Brian code removed) |
| 84 |
self._creation_stack = creation_stack[-1] |
| 85 |
self._full_creation_stack = "\n".join(creation_stack) |
| 86 |
|
| 87 |
if dt is not None and clock is not None: |
| 88 |
raise ValueError("Can only specify either a dt or a clock, not both.") |
| 89 |
|
| 90 |
if not isinstance(when, str): |
| 91 |
from brian2.core.clocks import Clock |
| 92 |
|
| 93 |
# Give some helpful error messages for users coming from the alpha |
| 94 |
# version |
| 95 |
if isinstance(when, Clock): |
| 96 |
raise TypeError( |
| 97 |
"Do not use the 'when' argument for " |
| 98 |
"specifying a clock, either provide a " |
| 99 |
"timestep for the 'dt' argument or a Clock " |
| 100 |
"object for 'clock'." |
| 101 |
) |
| 102 |
if isinstance(when, tuple): |
| 103 |
raise TypeError( |
| 104 |
"Use the separate keyword arguments, 'dt' (or " |
| 105 |
"'clock'), 'when', and 'order' instead of " |
| 106 |
"providing a tuple for 'when'. Only use the " |
| 107 |
"'when' argument for the scheduling slot." |
| 108 |
) |
| 109 |
# General error |
| 110 |
raise TypeError( |
| 111 |
"The 'when' argument has to be a string " |
| 112 |
"specifying the scheduling slot (e.g. 'start')." |
| 113 |
) |
| 114 |
|
| 115 |
Nameable.__init__(self, name) |
| 116 |
|
| 117 |
#: The clock used for simulating this object |
| 118 |
self._clock = clock |
| 119 |
if clock is None: |
| 120 |
from brian2.core.clocks import Clock, defaultclock |
| 121 |
|
| 122 |
if dt is not None: |
| 123 |
self._clock = Clock(dt=dt, name=self.name + "_clock*") |
| 124 |
else: |
| 125 |
self._clock = defaultclock |
| 126 |
|
| 127 |
if getattr(self._clock, "_is_proxy", False): |
| 128 |
from brian2.devices.device import get_device |
| 129 |
|
| 130 |
self._clock = get_device().defaultclock |
| 131 |
|
| 132 |
#: Used to remember the `Network` in which this object has been included |
| 133 |
#: before, to raise an error if it is included in a new `Network` |
| 134 |
self._network = None |
| 135 |
|
| 136 |
#: The ID string determining when the object should be updated in `Network.run`. |
| 137 |
self.when = when |
| 138 |
|
| 139 |
#: The order in which objects with the same clock and ``when`` should be updated |
| 140 |
self.order = order |
| 141 |
|
| 142 |
self._dependencies = set() |
| 143 |
self._contained_objects = [] |
| 144 |
self._code_objects = [] |
| 145 |
|
| 146 |
self._active = True |
| 147 |
|
| 148 |
#: The scope key is used to determine which objects are collected by magic |
| 149 |
self._scope_key = self._scope_current_key |
| 150 |
|
| 151 |
# Make sure that keys in the namespace are valid |
| 152 |
if namespace is None: |
| 153 |
# Do not overwrite namespace if already set (e.g. in StateMonitor) |
| 154 |
namespace = getattr(self, "namespace", {}) |
| 155 |
for key in namespace: |
| 156 |
if key.startswith("_"): |
| 157 |
raise ValueError( |
| 158 |
"Names starting with underscores are " |
| 159 |
"reserved for internal use an cannot be " |
| 160 |
"defined in the namespace argument." |
| 161 |
) |
| 162 |
#: The group-specific namespace |
| 163 |
self.namespace = namespace |
| 164 |
|
| 165 |
logger.diagnostic( |
| 166 |
f"Created BrianObject with name {self.name}, " |
| 167 |
f"clock={self._clock}, " |
| 168 |
f"when={self.when}, order={self.order}" |
| 169 |
) |
| 170 |
|
| 171 |
#: Global key value for ipython cell restrict magic |
| 172 |
_scope_current_key = 0 |
| 173 |
|
| 174 |
#: Whether or not `MagicNetwork` is invalidated when a new `BrianObject` of this type is added |
| 175 |
invalidates_magic_network = True |
| 176 |
|
| 177 |
#: Whether or not the object should be added to a `MagicNetwork`. Note that |
| 178 |
#: all objects in `BrianObject.contained_objects` are automatically added |
| 179 |
#: when the parent object is added, therefore e.g. `NeuronGroup` should set |
| 180 |
#: `add_to_magic_network` to ``True``, but it should not be set for all the |
| 181 |
#: dependent objects such as `StateUpdater` |
| 182 |
add_to_magic_network = False |
| 183 |
|
| 184 |
def __del__(self): |
| 185 |
# For objects that get garbage collected, raise a warning if they have |
| 186 |
# never been part of a network |
| 187 |
if ( |
| 188 |
prefs.logging.warn_for_unused_objects |
| 189 |
and getattr(self, "_network", "uninitialized") is None |
| 190 |
and getattr(self, "group", None) is None |
| 191 |
and not BrianLogger.exception_occured # No need to add a warning if something went wrong |
| 192 |
): |
| 193 |
logger.warn( |
| 194 |
f"The object '{self.name}' is getting deleted, but was never included in a network. " |
| 195 |
"This probably means that you did not store the object reference in a variable, " |
| 196 |
"or that the variable was not used to construct the network.\n" |
| 197 |
"The object was created here (most recent call only):\n" |
| 198 |
+ self._creation_stack, |
| 199 |
name_suffix="unused_brian_object", |
| 200 |
) |
| 201 |
|
| 202 |
def add_dependency(self, obj): |
| 203 |
""" |
| 204 |
Add an object to the list of dependencies. Takes care of handling |
| 205 |
subgroups correctly (i.e., adds its parent object). |
| 206 |
|
| 207 |
Parameters |
| 208 |
---------- |
| 209 |
obj : `BrianObject` |
| 210 |
The object that this object depends on. |
| 211 |
""" |
| 212 |
from brian2.groups.subgroup import Subgroup |
| 213 |
|
| 214 |
if isinstance(obj, Subgroup): |
| 215 |
self._dependencies.add(obj.source.id) |
| 216 |
else: |
| 217 |
self._dependencies.add(obj.id) |
| 218 |
|
| 219 |
def before_run(self, run_namespace): |
| 220 |
""" |
| 221 |
Optional method to prepare the object before a run. |
| 222 |
|
| 223 |
Called by `Network.after_run` before the main simulation loop starts. |
| 224 |
""" |
| 225 |
for codeobj in self._code_objects: |
| 226 |
codeobj.before_run() |
| 227 |
|
| 228 |
def after_run(self): |
| 229 |
""" |
| 230 |
Optional method to do work after a run is finished. |
| 231 |
|
| 232 |
Called by `Network.after_run` after the main simulation loop terminated. |
| 233 |
""" |
| 234 |
for codeobj in self._code_objects: |
| 235 |
codeobj.after_run() |
| 236 |
|
| 237 |
def run(self): |
| 238 |
for codeobj in self._code_objects: |
| 239 |
codeobj() |
| 240 |
|
| 241 |
contained_objects = property( |
| 242 |
fget=lambda self: self._contained_objects, |
| 243 |
doc=""" |
| 244 |
The list of objects contained within the `BrianObject`. |
| 245 |
|
| 246 |
When a `BrianObject` is added to a `Network`, its contained objects will |
| 247 |
be added as well. This allows for compound objects which contain |
| 248 |
a mini-network structure. |
| 249 |
|
| 250 |
Note that this attribute cannot be set directly, you need to modify |
| 251 |
the underlying list, e.g. ``obj.contained_objects.extend([A, B])``. |
| 252 |
""", |
| 253 |
) |
| 254 |
|
| 255 |
code_objects = property( |
| 256 |
fget=lambda self: self._code_objects, |
| 257 |
doc=""" |
| 258 |
The list of `CodeObject` contained within the `BrianObject`. |
| 259 |
|
| 260 |
TODO: more details. |
| 261 |
|
| 262 |
Note that this attribute cannot be set directly, you need to modify |
| 263 |
the underlying list, e.g. ``obj.code_objects.extend([A, B])``. |
| 264 |
""", |
| 265 |
) |
| 266 |
|
| 267 |
updaters = property( |
| 268 |
fget=lambda self: self._updaters, |
| 269 |
doc=""" |
| 270 |
The list of `Updater` that define the runtime behaviour of this object. |
| 271 |
|
| 272 |
TODO: more details. |
| 273 |
|
| 274 |
Note that this attribute cannot be set directly, you need to modify |
| 275 |
the underlying list, e.g. ``obj.updaters.extend([A, B])``. |
| 276 |
""", |
| 277 |
) |
| 278 |
|
| 279 |
clock = property( |
| 280 |
fget=lambda self: self._clock, |
| 281 |
doc=""" |
| 282 |
The `Clock` determining when the object should be updated. |
| 283 |
|
| 284 |
Note that this cannot be changed after the object is |
| 285 |
created. |
| 286 |
""", |
| 287 |
) |
| 288 |
|
| 289 |
def _set_active(self, val): |
| 290 |
val = bool(val) |
| 291 |
self._active = val |
| 292 |
for obj in self.contained_objects: |
| 293 |
obj.active = val |
| 294 |
|
| 295 |
active = property( |
| 296 |
fget=lambda self: self._active, |
| 297 |
fset=_set_active, |
| 298 |
doc=""" |
| 299 |
Whether or not the object should be run. |
| 300 |
|
| 301 |
Inactive objects will not have their `update` |
| 302 |
method called in `Network.run`. Note that setting or |
| 303 |
unsetting the `active` attribute will set or unset |
| 304 |
it for all `contained_objects`. |
| 305 |
""", |
| 306 |
) |
| 307 |
|
| 308 |
def __repr__(self): |
| 309 |
classname = self.__class__.__name__ |
| 310 |
description = ( |
| 311 |
f"{classname}(clock={self._clock}, when={self.when}, " |
| 312 |
f"order={self.order}, name={self.name!r})" |
| 313 |
) |
| 314 |
return description |
| 315 |
|
| 316 |
# This is a repeat from Nameable.name, but we want to get the documentation |
| 317 |
# here again |
| 318 |
name = Nameable.name |
| 319 |
|
| 320 |
|
| 321 |
def weakproxy_with_fallback(obj): |
| 322 |
""" |
| 323 |
Attempts to create a `weakproxy` to the object, but falls back to the object if not possible. |
| 324 |
""" |
| 325 |
try: |
| 326 |
return weakref.proxy(obj) |
| 327 |
except TypeError: |
| 328 |
return obj |
| 329 |
|
| 330 |
|
| 331 |
def device_override(name): |
| 332 |
""" |
| 333 |
Decorates a function/method to allow it to be overridden by the current `Device`. |
| 334 |
|
| 335 |
The ``name`` is the function name in the `Device` to use as an override if it exists. |
| 336 |
|
| 337 |
The returned function has an additional attribute ``original_function`` |
| 338 |
which is a reference to the original, undecorated function. |
| 339 |
""" |
| 340 |
|
| 341 |
def device_override_decorator(func): |
| 342 |
def device_override_decorated_function(*args, **kwds): |
| 343 |
from brian2.devices.device import get_device |
| 344 |
|
| 345 |
curdev = get_device() |
| 346 |
if hasattr(curdev, name): |
| 347 |
return getattr(curdev, name)(*args, **kwds) |
| 348 |
else: |
| 349 |
return func(*args, **kwds) |
| 350 |
|
| 351 |
device_override_decorated_function.original_function = func |
| 352 |
functools.update_wrapper(device_override_decorated_function, func) |
| 353 |
|
| 354 |
return device_override_decorated_function |
| 355 |
|
| 356 |
return device_override_decorator |
| 357 |
|
| 358 |
|
| 359 |
class BrianObjectException(Exception): |
| 360 |
""" |
| 361 |
High level exception that adds extra Brian-specific information to exceptions |
| 362 |
|
| 363 |
This exception should only be raised at a fairly high level in Brian code to |
| 364 |
pass information back to the user. It adds extra information about where a |
| 365 |
`BrianObject` was defined to better enable users to locate the source of |
| 366 |
problems. |
| 367 |
|
| 368 |
Parameters |
| 369 |
---------- |
| 370 |
|
| 371 |
message : str |
| 372 |
Additional error information to add to the original exception. |
| 373 |
brianobj : BrianObject |
| 374 |
The object that caused the error to happen. |
| 375 |
original_exception : Exception |
| 376 |
The original exception that was raised. |
| 377 |
""" |
| 378 |
|
| 379 |
def __init__(self, message, brianobj): |
| 380 |
self._brian_message = message |
| 381 |
self._brian_objname = brianobj.name |
| 382 |
self._brian_objcreate = ( |
| 383 |
"Object was created here (most recent call only, full details in " |
| 384 |
"debug log):\n" + brianobj._creation_stack |
| 385 |
) |
| 386 |
full_stack = "Object was created here:\n" + brianobj._full_creation_stack |
| 387 |
logger.diagnostic( |
| 388 |
f"Error was encountered with object '{self._brian_objname}':\n{full_stack}" |
| 389 |
) |
| 390 |
|
| 391 |
def __str__(self): |
| 392 |
return ( |
| 393 |
f"Error encountered with object named '{self._brian_objname}'.\n" |
| 394 |
f"{self._brian_objcreate}\n\n" |
| 395 |
f"{self._brian_message} " |
| 396 |
"(See above for original error message and traceback.)" |
| 397 |
) |
| 398 |
|
| 399 |
|
| 400 |
def brian_object_exception(message, brianobj, original_exception): |
| 401 |
""" |
| 402 |
Returns a `BrianObjectException` derived from the original exception. |
| 403 |
|
| 404 |
Creates a new class derived from the class of the original exception |
| 405 |
and `BrianObjectException`. This allows exception handling code to |
| 406 |
respond both to the original exception class and `BrianObjectException`. |
| 407 |
|
| 408 |
See `BrianObjectException` for arguments and notes. |
| 409 |
""" |
| 410 |
|
| 411 |
raise NotImplementedError( |
| 412 |
"The brian_object_exception function is no longer used. " |
| 413 |
"Raise a BrianObjectException directly." |
| 414 |
) |