| 1 |
""" |
| 2 |
This module defines the `VariableOwner` class, a mix-in class for everything |
| 3 |
that saves state variables, e.g. `Clock` or `NeuronGroup`, the class `Group` |
| 4 |
for objects that in addition to storing state variables also execute code, i.e. |
| 5 |
objects such as `NeuronGroup` or `StateMonitor` but not `Clock`, and finally |
| 6 |
`CodeRunner`, a class to run code in the context of a `Group`. |
| 7 |
""" |
| 8 |
|
| 9 |
import inspect |
| 10 |
import numbers |
| 11 |
import weakref |
| 12 |
from collections import OrderedDict |
| 13 |
from collections.abc import Mapping |
| 14 |
|
| 15 |
import numpy as np |
| 16 |
|
| 17 |
from brian2.codegen.codeobject import create_runner_codeobj |
| 18 |
from brian2.core.base import BrianObject, weakproxy_with_fallback |
| 19 |
from brian2.core.functions import Function |
| 20 |
from brian2.core.names import Nameable, find_name |
| 21 |
from brian2.core.namespace import ( |
| 22 |
DEFAULT_CONSTANTS, |
| 23 |
DEFAULT_FUNCTIONS, |
| 24 |
DEFAULT_UNITS, |
| 25 |
get_local_namespace, |
| 26 |
) |
| 27 |
from brian2.core.preferences import prefs |
| 28 |
from brian2.core.variables import ( |
| 29 |
ArrayVariable, |
| 30 |
AuxiliaryVariable, |
| 31 |
Constant, |
| 32 |
DynamicArrayVariable, |
| 33 |
LinkedVariable, |
| 34 |
Subexpression, |
| 35 |
Variable, |
| 36 |
Variables, |
| 37 |
) |
| 38 |
from brian2.equations.equations import BOOLEAN, FLOAT, INTEGER, Equations |
| 39 |
from brian2.importexport.importexport import ImportExport |
| 40 |
from brian2.units.fundamentalunits import ( |
| 41 |
DIMENSIONLESS, |
| 42 |
DimensionMismatchError, |
| 43 |
fail_for_dimension_mismatch, |
| 44 |
get_unit, |
| 45 |
) |
| 46 |
from brian2.utils.logger import get_logger |
| 47 |
from brian2.utils.stringtools import SpellChecker, get_identifiers |
| 48 |
|
| 49 |
__all__ = ["Group", "VariableOwner", "CodeRunner"] |
| 50 |
|
| 51 |
logger = get_logger(__name__) |
| 52 |
|
| 53 |
|
| 54 |
def _display_value(obj): |
| 55 |
""" |
| 56 |
Helper function for warning messages that display the value of objects. This |
| 57 |
functions returns a nicer representation for symbolic constants and |
| 58 |
functions. |
| 59 |
|
| 60 |
Parameters |
| 61 |
---------- |
| 62 |
obj : object |
| 63 |
The object to display |
| 64 |
|
| 65 |
Returns |
| 66 |
------- |
| 67 |
value : str |
| 68 |
A string representation of the object |
| 69 |
""" |
| 70 |
if isinstance(obj, Function): |
| 71 |
return "<Function>" |
| 72 |
try: |
| 73 |
obj = obj.get_value() |
| 74 |
except AttributeError: |
| 75 |
pass |
| 76 |
try: |
| 77 |
obj = obj.value |
| 78 |
except AttributeError: |
| 79 |
pass |
| 80 |
|
| 81 |
# We (temporarily) set numpy's print options so that array with more than |
| 82 |
# 10 elements are only shown in an abbreviated way |
| 83 |
old_options = np.get_printoptions() |
| 84 |
np.set_printoptions(threshold=10) |
| 85 |
try: |
| 86 |
str_repr = repr(obj) |
| 87 |
except Exception: |
| 88 |
str_repr = f"<object of type {type(obj)}>" |
| 89 |
finally: |
| 90 |
np.set_printoptions(**old_options) |
| 91 |
return str_repr |
| 92 |
|
| 93 |
|
| 94 |
def _conflict_warning(message, resolutions): |
| 95 |
""" |
| 96 |
A little helper functions to generate warnings for logging. Specific |
| 97 |
to the `Group._resolve` method and should only be used by it. |
| 98 |
|
| 99 |
Parameters |
| 100 |
---------- |
| 101 |
message : str |
| 102 |
The first part of the warning message. |
| 103 |
resolutions : list of str |
| 104 |
A list of (namespace, object) tuples. |
| 105 |
""" |
| 106 |
if len(resolutions) == 0: |
| 107 |
# nothing to warn about |
| 108 |
return |
| 109 |
elif len(resolutions) == 1: |
| 110 |
second_part = ( |
| 111 |
"but the name also refers to a variable in the " |
| 112 |
f"{resolutions[0][0]} " |
| 113 |
f"namespace with value '{_display_value(resolutions[0][1])}'." |
| 114 |
) |
| 115 |
else: |
| 116 |
second_part = ( |
| 117 |
"but the name also refers to a variable in the following " |
| 118 |
f"namespaces: {', '.join([r[0] for r in resolutions])}." |
| 119 |
) |
| 120 |
|
| 121 |
logger.warn( |
| 122 |
f"{message} {second_part}", "Group.resolve.resolution_conflict", once=True |
| 123 |
) |
| 124 |
|
| 125 |
|
| 126 |
def get_dtype(equation, dtype=None): |
| 127 |
""" |
| 128 |
Helper function to interpret the `dtype` keyword argument in `NeuronGroup` |
| 129 |
etc. |
| 130 |
|
| 131 |
Parameters |
| 132 |
---------- |
| 133 |
equation : `SingleEquation` |
| 134 |
The equation for which a dtype should be returned |
| 135 |
dtype : `dtype` or dict, optional |
| 136 |
Either the `dtype` to be used as a default dtype for all float variables |
| 137 |
(instead of the `core.default_float_dtype` preference) or a |
| 138 |
dictionary stating the `dtype` for some variables; all other variables |
| 139 |
will use the preference default |
| 140 |
|
| 141 |
Returns |
| 142 |
------- |
| 143 |
d : `dtype` |
| 144 |
The dtype for the variable defined in `equation` |
| 145 |
""" |
| 146 |
# Check explicitly provided dtype for compatibility with the variable type |
| 147 |
if isinstance(dtype, Mapping): |
| 148 |
if equation.varname in dtype: |
| 149 |
BASIC_TYPES = {BOOLEAN: "b", INTEGER: "iu", FLOAT: "f"} |
| 150 |
provided_dtype = np.dtype(dtype[equation.varname]) |
| 151 |
if provided_dtype.kind not in BASIC_TYPES[equation.var_type]: |
| 152 |
raise TypeError( |
| 153 |
"Error determining dtype for variable " |
| 154 |
f"{equation.varname}: {provided_dtype.name} is not " |
| 155 |
f"a correct type for {equation.var_type} variables" |
| 156 |
) |
| 157 |
else: |
| 158 |
return dtype[equation.varname] |
| 159 |
else: # continue as if no dtype had been specified at all |
| 160 |
dtype = None |
| 161 |
|
| 162 |
# Use default dtypes (or a provided standard dtype for floats) |
| 163 |
if equation.var_type == BOOLEAN: |
| 164 |
return bool |
| 165 |
elif equation.var_type == INTEGER: |
| 166 |
return prefs["core.default_integer_dtype"] |
| 167 |
elif equation.var_type == FLOAT: |
| 168 |
if dtype is not None: |
| 169 |
dtype = np.dtype(dtype) |
| 170 |
if not dtype.kind == "f": |
| 171 |
raise TypeError(f"{dtype} is not a valid floating point dtype.") |
| 172 |
return dtype |
| 173 |
else: |
| 174 |
return prefs["core.default_float_dtype"] |
| 175 |
else: |
| 176 |
raise ValueError( |
| 177 |
"Do not know how to determine a dtype for " |
| 178 |
f"variable '{equation.varname}' of type {equation.var_type}" |
| 179 |
) |
| 180 |
|
| 181 |
|
| 182 |
def _same_value(obj1, obj2): |
| 183 |
""" |
| 184 |
Helper function used during namespace resolution. |
| 185 |
""" |
| 186 |
if obj1 is obj2: |
| 187 |
return True |
| 188 |
try: |
| 189 |
obj1 = obj1.get_value() |
| 190 |
except (AttributeError, TypeError): |
| 191 |
pass |
| 192 |
|
| 193 |
try: |
| 194 |
obj2 = obj2.get_value() |
| 195 |
except (AttributeError, TypeError): |
| 196 |
pass |
| 197 |
|
| 198 |
return obj1 is obj2 |
| 199 |
|
| 200 |
|
| 201 |
def _same_function(func1, func2): |
| 202 |
""" |
| 203 |
Helper function, used during namespace resolution for comparing whether to |
| 204 |
functions are the same. This takes care of treating a function and a |
| 205 |
`Function` variables whose `Function.pyfunc` attribute matches as the |
| 206 |
same. This prevents the user from getting spurious warnings when having |
| 207 |
for example a numpy function such as :np:func:`~random.randn` in the local |
| 208 |
namespace, while the ``randn`` symbol in the numpy namespace used for the |
| 209 |
code objects refers to a `RandnFunction` specifier. |
| 210 |
""" |
| 211 |
# use the function itself if it doesn't have a pyfunc attribute |
| 212 |
func1 = getattr(func1, "pyfunc", func1) |
| 213 |
func2 = getattr(func2, "pyfunc", func2) |
| 214 |
|
| 215 |
return func1 is func2 |
| 216 |
|
| 217 |
|
| 218 |
class Indexing: |
| 219 |
""" |
| 220 |
Object responsible for calculating flat index arrays from arbitrary group- |
| 221 |
specific indices. Stores strong references to the necessary variables so |
| 222 |
that basic indexing (i.e. slicing, integer arrays/values, ...) works even |
| 223 |
when the respective `VariableOwner` no longer exists. Note that this object |
| 224 |
does not handle string indexing. |
| 225 |
""" |
| 226 |
|
| 227 |
def __init__(self, group, default_index="_idx"): |
| 228 |
self.group = weakref.proxy(group) |
| 229 |
self.N = group.variables["N"] |
| 230 |
self.default_index = default_index |
| 231 |
|
| 232 |
def __call__(self, item=slice(None), index_var=None): # noqa: B008 |
| 233 |
""" |
| 234 |
Return flat indices to index into state variables from arbitrary |
| 235 |
group specific indices. In the default implementation, raises an error |
| 236 |
for multidimensional indices and transforms slices into arrays. |
| 237 |
|
| 238 |
Parameters |
| 239 |
---------- |
| 240 |
item : slice, array, int |
| 241 |
The indices to translate. |
| 242 |
|
| 243 |
Returns |
| 244 |
------- |
| 245 |
indices : `numpy.ndarray` |
| 246 |
The flat indices corresponding to the indices given in `item`. |
| 247 |
|
| 248 |
See Also |
| 249 |
-------- |
| 250 |
SynapticIndexing |
| 251 |
""" |
| 252 |
if index_var is None: |
| 253 |
index_var = self.default_index |
| 254 |
|
| 255 |
if hasattr(item, "_indices"): |
| 256 |
item = item._indices() |
| 257 |
|
| 258 |
if isinstance(item, tuple): |
| 259 |
raise IndexError( |
| 260 |
f"Can only interpret 1-d indices, got {len(item)} dimensions." |
| 261 |
) |
| 262 |
else: |
| 263 |
if isinstance(item, str) and item == "True": |
| 264 |
item = slice(None) |
| 265 |
if isinstance(item, slice): |
| 266 |
if index_var == "0": |
| 267 |
return 0 |
| 268 |
if index_var == "_idx": |
| 269 |
start, stop, step = item.indices(self.N.item()) |
| 270 |
else: |
| 271 |
start, stop, step = item.indices(index_var.size) |
| 272 |
index_array = np.arange(start, stop, step, dtype=np.int32) |
| 273 |
else: |
| 274 |
index_array = np.asarray(item) |
| 275 |
if index_array.dtype == bool: |
| 276 |
index_array = np.nonzero(index_array)[0] |
| 277 |
elif not np.issubdtype(index_array.dtype, np.signedinteger): |
| 278 |
raise TypeError( |
| 279 |
"Indexing is only supported for integer " |
| 280 |
"and boolean arrays, not for type " |
| 281 |
f"{index_array.dtype}" |
| 282 |
) |
| 283 |
|
| 284 |
if index_var != "_idx": |
| 285 |
try: |
| 286 |
return index_var.get_value()[index_array] |
| 287 |
except IndexError as ex: |
| 288 |
# We try to emulate numpy's indexing semantics here: |
| 289 |
# slices never lead to IndexErrors, instead they return an |
| 290 |
# empty array if they don't match anything |
| 291 |
if isinstance(item, slice): |
| 292 |
return np.array([], dtype=np.int32) |
| 293 |
else: |
| 294 |
raise ex |
| 295 |
else: |
| 296 |
return index_array |
| 297 |
|
| 298 |
|
| 299 |
class IndexWrapper: |
| 300 |
""" |
| 301 |
Convenience class to allow access to the indices via indexing syntax. This |
| 302 |
allows for example to get all indices for synapses originating from neuron |
| 303 |
10 by writing `synapses.indices[10, :]` instead of |
| 304 |
`synapses._indices.((10, slice(None))`. |
| 305 |
""" |
| 306 |
|
| 307 |
def __init__(self, group): |
| 308 |
self.group = weakref.proxy(group) |
| 309 |
self.indices = group._indices |
| 310 |
|
| 311 |
def __getitem__(self, item): |
| 312 |
if isinstance(item, str): |
| 313 |
variables = Variables(None) |
| 314 |
variables.add_auxiliary_variable("_indices", dtype=np.int32) |
| 315 |
variables.add_auxiliary_variable("_cond", dtype=bool) |
| 316 |
|
| 317 |
abstract_code = f"_cond = {item}" |
| 318 |
namespace = get_local_namespace(level=1) |
| 319 |
from brian2.devices.device import get_device |
| 320 |
|
| 321 |
device = get_device() |
| 322 |
codeobj = create_runner_codeobj( |
| 323 |
self.group, |
| 324 |
abstract_code, |
| 325 |
"group_get_indices", |
| 326 |
run_namespace=namespace, |
| 327 |
additional_variables=variables, |
| 328 |
codeobj_class=device.code_object_class( |
| 329 |
fallback_pref="codegen.string_expression_target" |
| 330 |
), |
| 331 |
) |
| 332 |
return codeobj() |
| 333 |
else: |
| 334 |
return self.indices(item) |
| 335 |
|
| 336 |
|
| 337 |
class VariableOwner(Nameable): |
| 338 |
""" |
| 339 |
Mix-in class for accessing arrays by attribute. |
| 340 |
|
| 341 |
# TODO: Overwrite the __dir__ method to return the state variables |
| 342 |
# (should make autocompletion work) |
| 343 |
""" |
| 344 |
|
| 345 |
def _enable_group_attributes(self): |
| 346 |
if not hasattr(self, "variables"): |
| 347 |
raise ValueError( |
| 348 |
"Classes derived from VariableOwner need a variables attribute." |
| 349 |
) |
| 350 |
if "N" not in self.variables: |
| 351 |
raise ValueError("Each VariableOwner needs an 'N' variable.") |
| 352 |
if not hasattr(self, "codeobj_class"): |
| 353 |
self.codeobj_class = None |
| 354 |
if not hasattr(self, "_indices"): |
| 355 |
self._indices = Indexing(self) |
| 356 |
if not hasattr(self, "indices"): |
| 357 |
self.indices = IndexWrapper(self) |
| 358 |
if not hasattr(self, "_stored_states"): |
| 359 |
self._stored_states = {} |
| 360 |
self._group_attribute_access_active = True |
| 361 |
|
| 362 |
def state(self, name, use_units=True, level=0): |
| 363 |
""" |
| 364 |
Return the state variable in a way that properly supports indexing in |
| 365 |
the context of this group |
| 366 |
|
| 367 |
Parameters |
| 368 |
---------- |
| 369 |
name : str |
| 370 |
The name of the state variable |
| 371 |
use_units : bool, optional |
| 372 |
Whether to use the state variable's unit. |
| 373 |
level : int, optional |
| 374 |
How much farther to go down in the stack to find the namespace. |
| 375 |
Returns |
| 376 |
------- |
| 377 |
var : `VariableView` or scalar value |
| 378 |
The state variable's value that can be indexed (for non-scalar |
| 379 |
values). |
| 380 |
""" |
| 381 |
try: |
| 382 |
var = self.variables[name] |
| 383 |
except KeyError as exc: |
| 384 |
raise KeyError(f"State variable {name} not found.") from exc |
| 385 |
|
| 386 |
if use_units: |
| 387 |
return var.get_addressable_value_with_unit(name=name, group=self) |
| 388 |
else: |
| 389 |
return var.get_addressable_value(name=name, group=self) |
| 390 |
|
| 391 |
def __getattr__(self, name): |
| 392 |
# We do this because __setattr__ and __getattr__ are not active until |
| 393 |
# _group_attribute_access_active attribute is set, and if it is set, |
| 394 |
# then __getattr__ will not be called. Therefore, if getattr is called |
| 395 |
# with this name, it is because it hasn't been set yet and so this |
| 396 |
# method should raise an AttributeError to agree that it hasn't been |
| 397 |
# called yet. |
| 398 |
if name == "_group_attribute_access_active": |
| 399 |
raise AttributeError |
| 400 |
if "_group_attribute_access_active" not in self.__dict__: |
| 401 |
raise AttributeError |
| 402 |
if ( |
| 403 |
name in self.__getattribute__("__dict__") |
| 404 |
or name in self.__getattribute__("__class__").__dict__ |
| 405 |
): |
| 406 |
# Makes sure that classes can override the "variables" mechanism |
| 407 |
# with instance/class attributes and properties |
| 408 |
return object.__getattribute__(self, name) |
| 409 |
# We want to make sure that accessing variables without units is fast |
| 410 |
# because this is what is used during simulations |
| 411 |
# We do not specifically check for len(name) here, we simply assume |
| 412 |
# that __getattr__ is not called with an empty string (which wouldn't |
| 413 |
# be possible using the normal dot syntax, anyway) |
| 414 |
try: |
| 415 |
if name[-1] == "_": |
| 416 |
name = name[:-1] |
| 417 |
use_units = False |
| 418 |
else: |
| 419 |
use_units = True |
| 420 |
return self.state(name, use_units) |
| 421 |
|
| 422 |
except KeyError as ex: |
| 423 |
raise AttributeError(f"No attribute with name {name}") from ex |
| 424 |
|
| 425 |
def __setattr__(self, key, value, level=0): |
| 426 |
# attribute access is switched off until this attribute is created by |
| 427 |
# _enable_group_attributes |
| 428 |
if not hasattr(self, "_group_attribute_access_active") or key in self.__dict__: |
| 429 |
object.__setattr__(self, key, value) |
| 430 |
elif key in getattr(self, "_linked_variables", set()): |
| 431 |
if not isinstance(value, LinkedVariable): |
| 432 |
raise ValueError( |
| 433 |
"Cannot set a linked variable directly, link " |
| 434 |
"it to another variable using 'linked_var'." |
| 435 |
) |
| 436 |
linked_var = value.variable |
| 437 |
|
| 438 |
eq = self.equations[key] |
| 439 |
if eq.dim is not linked_var.dim: |
| 440 |
raise DimensionMismatchError( |
| 441 |
f"Unit of variable '{key}' does not " |
| 442 |
"match its link target " |
| 443 |
f"'{linked_var.name}'" |
| 444 |
) |
| 445 |
|
| 446 |
if not isinstance(linked_var, Subexpression): |
| 447 |
var_length = len(linked_var) |
| 448 |
else: |
| 449 |
var_length = len(linked_var.owner) |
| 450 |
|
| 451 |
if value.index is not None: |
| 452 |
index = self._linked_var_index(key, value, var_length) |
| 453 |
else: |
| 454 |
index = self._linked_var_automatic_index(key, value, var_length) |
| 455 |
self.variables.add_reference(key, value.group, value.name, index=index) |
| 456 |
source = (value.variable.owner.name,) |
| 457 |
sourcevar = value.variable.name |
| 458 |
log_msg = f"Setting {self.name}.{key} as a link to {source}.{sourcevar}" |
| 459 |
if index is not None: |
| 460 |
log_msg += f'(using "{index}" as index variable)' |
| 461 |
logger.diagnostic(log_msg) |
| 462 |
else: |
| 463 |
if isinstance(value, LinkedVariable): |
| 464 |
raise TypeError( |
| 465 |
f"Cannot link variable '{key}', it has to be marked " |
| 466 |
"as a linked variable with '(linked)' in the model " |
| 467 |
"equations." |
| 468 |
) |
| 469 |
else: |
| 470 |
if ( |
| 471 |
key in self.__getattribute__("__dict__") |
| 472 |
or key in self.__getattribute__("__class__").__dict__ |
| 473 |
): |
| 474 |
# Makes sure that classes can override the "variables" mechanism |
| 475 |
# with instance/class attributes and properties |
| 476 |
return object.__setattr__(self, key, value) |
| 477 |
elif key in self.variables: |
| 478 |
var = self.variables[key] |
| 479 |
if not isinstance(value, str): |
| 480 |
if var.dim is DIMENSIONLESS: |
| 481 |
fail_for_dimension_mismatch( |
| 482 |
value, |
| 483 |
var.dim, |
| 484 |
"%s should be set with a dimensionless value, but got {value}" |
| 485 |
% key, |
| 486 |
value=value, |
| 487 |
) |
| 488 |
else: |
| 489 |
fail_for_dimension_mismatch( |
| 490 |
value, |
| 491 |
var.dim, |
| 492 |
"%s should be set with a value with units %r, but got {value}" |
| 493 |
% (key, get_unit(var.dim)), |
| 494 |
value=value, |
| 495 |
) |
| 496 |
if var.read_only: |
| 497 |
raise TypeError(f"Variable {key} is read-only.") |
| 498 |
# Make the call X.var = ... equivalent to X.var[:] = ... |
| 499 |
var.get_addressable_value_with_unit(key, self).set_item( |
| 500 |
slice(None), value, level=level + 1 |
| 501 |
) |
| 502 |
elif len(key) and key[-1] == "_" and key[:-1] in self.variables: |
| 503 |
# no unit checking |
| 504 |
var = self.variables[key[:-1]] |
| 505 |
if var.read_only: |
| 506 |
raise TypeError(f"Variable {key[:-1]} is read-only.") |
| 507 |
# Make the call X.var = ... equivalent to X.var[:] = ... |
| 508 |
var.get_addressable_value(key[:-1], self).set_item( |
| 509 |
slice(None), value, level=level + 1 |
| 510 |
) |
| 511 |
elif hasattr(self, key) or key.startswith("_"): |
| 512 |
object.__setattr__(self, key, value) |
| 513 |
else: |
| 514 |
# Try to suggest the correct name in case of a typo |
| 515 |
checker = SpellChecker( |
| 516 |
[ |
| 517 |
varname |
| 518 |
for varname, var in self.variables.items() |
| 519 |
if not (varname.startswith("_") or var.read_only) |
| 520 |
] |
| 521 |
) |
| 522 |
if key.endswith("_"): |
| 523 |
suffix = "_" |
| 524 |
key = key[:-1] |
| 525 |
else: |
| 526 |
suffix = "" |
| 527 |
error_msg = f'Could not find a state variable with name "{key}".' |
| 528 |
suggestions = checker.suggest(key) |
| 529 |
if len(suggestions) == 1: |
| 530 |
(suggestion,) = suggestions |
| 531 |
error_msg += f' Did you mean to write "{suggestion}{suffix}"?' |
| 532 |
elif len(suggestions) > 1: |
| 533 |
suggestion_str = ", ".join( |
| 534 |
[f"'{suggestion}{suffix}'" for suggestion in suggestions] |
| 535 |
) |
| 536 |
error_msg += f" Did you mean to write any of the following: {suggestion_str} ?" |
| 537 |
error_msg += ( |
| 538 |
" Use the add_attribute method if you intend to add " |
| 539 |
"a new attribute to the object." |
| 540 |
) |
| 541 |
raise AttributeError(error_msg) |
| 542 |
|
| 543 |
def _linked_var_automatic_index(self, var_name, linked_var, var_length): |
| 544 |
# The check at the end is to avoid the case that a size 1 NeuronGroup |
| 545 |
# links to another NeuronGroup of size 1 and cannot do certain operations |
| 546 |
# since the linked variable is considered scalar. |
| 547 |
if linked_var.variable.scalar or ( |
| 548 |
var_length == 1 and getattr(self, "_N", 0) != 1 |
| 549 |
): |
| 550 |
index = "0" |
| 551 |
else: |
| 552 |
index = linked_var.group.variables.indices[linked_var.name] |
| 553 |
if index == "_idx": |
| 554 |
target_length = var_length |
| 555 |
else: |
| 556 |
target_length = len(linked_var.group.variables[index]) |
| 557 |
# we need a name for the index that does not clash with |
| 558 |
# other names and a reference to the index |
| 559 |
new_index = f"_{linked_var.name}_index_{index}" |
| 560 |
self.variables.add_reference(new_index, linked_var.group, index) |
| 561 |
index = new_index |
| 562 |
|
| 563 |
if len(self) != target_length: |
| 564 |
raise ValueError( |
| 565 |
f"Cannot link variable '{var_name}' to " |
| 566 |
f"'{linked_var.variable.name}', the size of the " |
| 567 |
"target group does not match " |
| 568 |
f"({len(self)} != {target_length}). You can " |
| 569 |
"provide an indexing scheme with the " |
| 570 |
"'index' keyword to link groups with " |
| 571 |
"different sizes" |
| 572 |
) |
| 573 |
return index |
| 574 |
|
| 575 |
def _linked_var_index(self, var_name, linked_var, target_size): |
| 576 |
if isinstance(linked_var.index, str): |
| 577 |
if linked_var.index not in self.variables: |
| 578 |
raise ValueError(f"Index variable '{linked_var.index}' not found.") |
| 579 |
if self.variables.indices[linked_var.index] != self.variables.default_index: |
| 580 |
raise ValueError( |
| 581 |
f"Index variable '{linked_var.index}' should use the default index itself." |
| 582 |
) |
| 583 |
if not np.issubdtype(self.variables[linked_var.index].dtype, np.integer): |
| 584 |
raise TypeError( |
| 585 |
f"Index variable '{linked_var.index}' should be an integer parameter." |
| 586 |
) |
| 587 |
index = linked_var.index |
| 588 |
else: |
| 589 |
# Index arrays are not allowed for classes with dynamic size (Synapses) |
| 590 |
if not isinstance(self.variables["N"], Constant): |
| 591 |
raise TypeError( |
| 592 |
"Cannot link a variable with an index array for a class with dynamic size – use a variable name instead." |
| 593 |
) |
| 594 |
try: |
| 595 |
index_array = np.asarray(linked_var.index) |
| 596 |
if not np.issubdtype(index_array.dtype, int): |
| 597 |
raise TypeError() |
| 598 |
except TypeError: |
| 599 |
raise TypeError( |
| 600 |
"The index for a linked variable has to be an integer array" |
| 601 |
) from None |
| 602 |
size = len(index_array) |
| 603 |
source_index = linked_var.group.variables.indices[linked_var.name] |
| 604 |
if source_index not in ("_idx", "0"): |
| 605 |
# we are indexing into an already indexed variable, |
| 606 |
# calculate the indexing into the target variable |
| 607 |
index_array = linked_var.group.variables[source_index].get_value()[ |
| 608 |
index_array |
| 609 |
] |
| 610 |
|
| 611 |
if not index_array.ndim == 1 or size != len(self): |
| 612 |
raise TypeError( |
| 613 |
f"Index array for linked variable '{var_name}' " |
| 614 |
"has to be a one-dimensional array of " |
| 615 |
f"length {len(self)}, but has shape " |
| 616 |
f"{index_array.shape!s}" |
| 617 |
) |
| 618 |
if min(index_array) < 0 or max(index_array) >= target_size: |
| 619 |
raise ValueError( |
| 620 |
f"Index array for linked variable {var_name} " |
| 621 |
"contains values outside of the valid " |
| 622 |
f"range [0, {target_size}[" |
| 623 |
) |
| 624 |
self.variables.add_array( |
| 625 |
f"_{var_name}_indices", |
| 626 |
size=size, |
| 627 |
dtype=index_array.dtype, |
| 628 |
constant=True, |
| 629 |
read_only=True, |
| 630 |
values=index_array, |
| 631 |
) |
| 632 |
index = f"_{var_name}_indices" |
| 633 |
return index |
| 634 |
|
| 635 |
def add_attribute(self, name): |
| 636 |
""" |
| 637 |
Add a new attribute to this group. Using this method instead of simply |
| 638 |
assigning to the new attribute name is necessary because Brian will |
| 639 |
raise an error in that case, to avoid bugs passing unnoticed |
| 640 |
(misspelled state variable name, un-declared state variable, ...). |
| 641 |
|
| 642 |
Parameters |
| 643 |
---------- |
| 644 |
name : str |
| 645 |
The name of the new attribute |
| 646 |
|
| 647 |
Raises |
| 648 |
------ |
| 649 |
AttributeError |
| 650 |
If the name already exists as an attribute or a state variable. |
| 651 |
""" |
| 652 |
if name in self.variables: |
| 653 |
raise AttributeError( |
| 654 |
f'Cannot add an attribute "{name}", it is already a state variable of' |
| 655 |
" this group." |
| 656 |
) |
| 657 |
if hasattr(self, name): |
| 658 |
raise AttributeError( |
| 659 |
f'Cannot add an attribute "{name}", it is already an attribute of this' |
| 660 |
" group." |
| 661 |
) |
| 662 |
object.__setattr__(self, name, None) |
| 663 |
|
| 664 |
def get_states( |
| 665 |
self, |
| 666 |
vars=None, |
| 667 |
units=True, |
| 668 |
format="dict", |
| 669 |
subexpressions=False, |
| 670 |
read_only_variables=True, |
| 671 |
level=0, |
| 672 |
): |
| 673 |
""" |
| 674 |
Return a copy of the current state variable values. The returned arrays |
| 675 |
are copies of the actual arrays that store the state variable values, |
| 676 |
therefore changing the values in the returned dictionary will not affect |
| 677 |
the state variables. |
| 678 |
|
| 679 |
Parameters |
| 680 |
---------- |
| 681 |
vars : list of str, optional |
| 682 |
The names of the variables to extract. If not specified, extract |
| 683 |
all state variables (except for internal variables, i.e. names that |
| 684 |
start with ``'_'``). If the ``subexpressions`` argument is ``True``, |
| 685 |
the current values of all subexpressions are returned as well. |
| 686 |
units : bool, optional |
| 687 |
Whether to include the physical units in the return value. Defaults |
| 688 |
to ``True``. |
| 689 |
format : str, optional |
| 690 |
The output format. Defaults to ``'dict'``. |
| 691 |
subexpressions: bool, optional |
| 692 |
Whether to return subexpressions when no list of variable names |
| 693 |
is given. Defaults to ``False``. This argument is ignored if an |
| 694 |
explicit list of variable names is given in ``vars``. |
| 695 |
read_only_variables : bool, optional |
| 696 |
Whether to return read-only variables (e.g. the number of neurons, |
| 697 |
the time, etc.). Setting it to ``False`` will assure that the |
| 698 |
returned state can later be used with `set_states`. Defaults to |
| 699 |
``True``. |
| 700 |
level : int, optional |
| 701 |
How much higher to go up the stack to resolve external variables. |
| 702 |
Only relevant if extracting subexpressions that refer to external |
| 703 |
variables. |
| 704 |
|
| 705 |
Returns |
| 706 |
------- |
| 707 |
values : dict or specified format |
| 708 |
The variables specified in ``vars``, in the specified ``format``. |
| 709 |
|
| 710 |
""" |
| 711 |
if format not in ImportExport.methods: |
| 712 |
raise NotImplementedError(f"Format '{format}' is not supported") |
| 713 |
if vars is None: |
| 714 |
vars = [] |
| 715 |
for name, var in self.variables.items(): |
| 716 |
if name.startswith("_"): |
| 717 |
continue |
| 718 |
if subexpressions or not isinstance(var, Subexpression): |
| 719 |
if read_only_variables or not getattr(var, "read_only", False): |
| 720 |
if not isinstance(var, AuxiliaryVariable): |
| 721 |
vars.append(name) |
| 722 |
data = ImportExport.methods[format].export_data( |
| 723 |
self, vars, units=units, level=level |
| 724 |
) |
| 725 |
return data |
| 726 |
|
| 727 |
def set_states(self, values, units=True, format="dict", level=0): |
| 728 |
""" |
| 729 |
Set the state variables. |
| 730 |
|
| 731 |
Parameters |
| 732 |
---------- |
| 733 |
values : depends on ``format`` |
| 734 |
The values according to ``format``. |
| 735 |
units : bool, optional |
| 736 |
Whether the ``values`` include physical units. Defaults to ``True``. |
| 737 |
format : str, optional |
| 738 |
The format of ``values``. Defaults to ``'dict'`` |
| 739 |
level : int, optional |
| 740 |
How much higher to go up the stack to resolve external variables. |
| 741 |
Only relevant when using string expressions to set values. |
| 742 |
""" |
| 743 |
# For the moment, 'dict' is the only supported format -- later this will |
| 744 |
# be made into an extensible system, see github issue #306 |
| 745 |
if format not in ImportExport.methods: |
| 746 |
raise NotImplementedError(f"Format '{format}' is not supported") |
| 747 |
ImportExport.methods[format].import_data(self, values, units=units, level=level) |
| 748 |
|
| 749 |
def check_variable_write(self, variable): |
| 750 |
""" |
| 751 |
Function that can be overwritten to raise an error if writing to a |
| 752 |
variable should not be allowed. Note that this does *not* deal with |
| 753 |
incorrect writes that are general to all kind of variables (incorrect |
| 754 |
units, writing to a read-only variable, etc.). This function is only |
| 755 |
used for type-specific rules, e.g. for raising an error in `Synapses` |
| 756 |
when writing to a synaptic variable before any `~Synapses.connect` |
| 757 |
call. |
| 758 |
|
| 759 |
By default this function does nothing. |
| 760 |
|
| 761 |
Parameters |
| 762 |
---------- |
| 763 |
variable : `Variable` |
| 764 |
The variable that the user attempts to set. |
| 765 |
""" |
| 766 |
pass |
| 767 |
|
| 768 |
def _full_state(self): |
| 769 |
state = {} |
| 770 |
for var in self.variables.values(): |
| 771 |
if not isinstance(var, ArrayVariable): |
| 772 |
continue # we are only interested in arrays |
| 773 |
if var.owner is None or var.owner.name != self.name: |
| 774 |
continue # we only store the state of our own variables |
| 775 |
|
| 776 |
state[var.name] = (var.get_value().copy(), var.size) |
| 777 |
|
| 778 |
return state |
| 779 |
|
| 780 |
def _restore_from_full_state(self, state): |
| 781 |
for var_name, (values, size) in state.items(): |
| 782 |
var = self.variables[var_name] |
| 783 |
if isinstance(var, DynamicArrayVariable): |
| 784 |
var.resize(size) |
| 785 |
var.set_value(values) |
| 786 |
|
| 787 |
def _check_expression_scalar(self, expr, varname, level=0, run_namespace=None): |
| 788 |
""" |
| 789 |
Helper function to check that an expression only refers to scalar |
| 790 |
variables, used when setting a scalar variable with a string expression. |
| 791 |
|
| 792 |
Parameters |
| 793 |
---------- |
| 794 |
expr : str |
| 795 |
The expression to check. |
| 796 |
varname : str |
| 797 |
The variable that is being set (only used for the error message) |
| 798 |
level : int, optional |
| 799 |
How far to go up in the stack to find the local namespace (if |
| 800 |
`run_namespace` is not set). |
| 801 |
run_namespace : dict-like, optional |
| 802 |
A specific namespace provided for this expression. |
| 803 |
|
| 804 |
Raises |
| 805 |
------ |
| 806 |
ValueError |
| 807 |
If the expression refers to a non-scalar variable. |
| 808 |
""" |
| 809 |
identifiers = get_identifiers(expr) |
| 810 |
referred_variables = self.resolve_all( |
| 811 |
identifiers, run_namespace=run_namespace, level=level + 1 |
| 812 |
) |
| 813 |
for ref_varname, ref_var in referred_variables.items(): |
| 814 |
if not getattr(ref_var, "scalar", False): |
| 815 |
raise ValueError( |
| 816 |
"String expression for setting scalar " |
| 817 |
f"variable '{varname} refers to '{ref_varname} which " |
| 818 |
"is not scalar." |
| 819 |
) |
| 820 |
|
| 821 |
def __len__(self): |
| 822 |
return self.variables["N"].item() |
| 823 |
|
| 824 |
|
| 825 |
class Group(VariableOwner, BrianObject): |
| 826 |
def _resolve( |
| 827 |
self, identifier, run_namespace, user_identifier=True, additional_variables=None |
| 828 |
): |
| 829 |
""" |
| 830 |
Resolve an identifier (i.e. variable, constant or function name) in the |
| 831 |
context of this group. This function will first lookup the name in the |
| 832 |
state variables, then look for a standard function or unit of that |
| 833 |
name and finally look in `Group.namespace` and in `run_namespace`. If |
| 834 |
the latter is not given, it will try to find the variable in the local |
| 835 |
namespace where the original function call took place. See |
| 836 |
:ref:`external-variables`. |
| 837 |
|
| 838 |
Parameters |
| 839 |
---------- |
| 840 |
identifiers : str |
| 841 |
The name to look up. |
| 842 |
run_namespace : dict-like, optional |
| 843 |
An additional namespace that is used for variable lookup (if not |
| 844 |
defined, the implicit namespace of local variables is used). |
| 845 |
user_identifier : bool, optional |
| 846 |
Whether this is an identifier that was used by the user (and not |
| 847 |
something automatically generated that the user might not even |
| 848 |
know about). Will be used to determine whether to display a |
| 849 |
warning in the case of namespace clashes. Defaults to ``True``. |
| 850 |
additional_variables : dict-like, optional |
| 851 |
An additional mapping of names to `Variable` objects that will be |
| 852 |
checked before `Group.variables`. |
| 853 |
|
| 854 |
Returns |
| 855 |
------- |
| 856 |
obj : `Variable` or `Function` |
| 857 |
Returns a `Variable` object describing the variable or a `Function` |
| 858 |
object for a function. External variables are represented as |
| 859 |
`Constant` objects |
| 860 |
|
| 861 |
Raises |
| 862 |
------ |
| 863 |
KeyError |
| 864 |
If the `identifier` could not be resolved |
| 865 |
""" |
| 866 |
resolved_internal = None |
| 867 |
|
| 868 |
if identifier in (additional_variables or {}): |
| 869 |
resolved_internal = additional_variables[identifier] |
| 870 |
elif identifier in getattr(self, "variables", {}): |
| 871 |
resolved_internal = self.variables[identifier] |
| 872 |
|
| 873 |
if resolved_internal is not None: |
| 874 |
if not user_identifier: |
| 875 |
return resolved_internal # no need to go further |
| 876 |
# We already found the identifier, but we try to resolve it in the |
| 877 |
# external namespace nevertheless, to report a warning if it is |
| 878 |
# present there as well. |
| 879 |
self._resolve_external( |
| 880 |
identifier, |
| 881 |
run_namespace=run_namespace, |
| 882 |
internal_variable=resolved_internal, |
| 883 |
) |
| 884 |
return resolved_internal |
| 885 |
|
| 886 |
# We did not find the name internally, try to resolve it in the external |
| 887 |
# namespace |
| 888 |
return self._resolve_external(identifier, run_namespace=run_namespace) |
| 889 |
|
| 890 |
def resolve_all( |
| 891 |
self, |
| 892 |
identifiers, |
| 893 |
run_namespace, |
| 894 |
user_identifiers=None, |
| 895 |
additional_variables=None, |
| 896 |
): |
| 897 |
""" |
| 898 |
Resolve a list of identifiers. Calls `Group._resolve` for each |
| 899 |
identifier. |
| 900 |
|
| 901 |
Parameters |
| 902 |
---------- |
| 903 |
identifiers : iterable of str |
| 904 |
The names to look up. |
| 905 |
run_namespace : dict-like, optional |
| 906 |
An additional namespace that is used for variable lookup (if not |
| 907 |
defined, the implicit namespace of local variables is used). |
| 908 |
user_identifiers : iterable of str, optional |
| 909 |
The names in ``identifiers`` that were provided by the user (i.e. |
| 910 |
are part of user-specified equations, abstract code, etc.). Will |
| 911 |
be used to determine when to issue namespace conflict warnings. If |
| 912 |
not specified, will be assumed to be identical to ``identifiers``. |
| 913 |
additional_variables : dict-like, optional |
| 914 |
An additional mapping of names to `Variable` objects that will be |
| 915 |
checked before `Group.variables`. |
| 916 |
|
| 917 |
Returns |
| 918 |
------- |
| 919 |
variables : dict of `Variable` or `Function` |
| 920 |
A mapping from name to `Variable`/`Function` object for each of the |
| 921 |
names given in `identifiers` |
| 922 |
|
| 923 |
Raises |
| 924 |
------ |
| 925 |
KeyError |
| 926 |
If one of the names in `identifier` cannot be resolved |
| 927 |
""" |
| 928 |
if user_identifiers is None: |
| 929 |
user_identifiers = identifiers |
| 930 |
assert isinstance(run_namespace, Mapping) |
| 931 |
resolved = {} |
| 932 |
for identifier in identifiers: |
| 933 |
resolved[identifier] = self._resolve( |
| 934 |
identifier, |
| 935 |
user_identifier=identifier in user_identifiers, |
| 936 |
additional_variables=additional_variables, |
| 937 |
run_namespace=run_namespace, |
| 938 |
) |
| 939 |
return resolved |
| 940 |
|
| 941 |
def _resolve_external( |
| 942 |
self, identifier, run_namespace, user_identifier=True, internal_variable=None |
| 943 |
): |
| 944 |
""" |
| 945 |
Resolve an external identifier in the context of a `Group`. If the `Group` |
| 946 |
declares an explicit namespace, this namespace is used in addition to the |
| 947 |
standard namespace for units and functions. Additionally, the namespace in |
| 948 |
the `run_namespace` argument (i.e. the namespace provided to `Network.run`) |
| 949 |
is used. |
| 950 |
|
| 951 |
Parameters |
| 952 |
---------- |
| 953 |
identifier : str |
| 954 |
The name to resolve. |
| 955 |
group : `Group` |
| 956 |
The group that potentially defines an explicit namespace for looking up |
| 957 |
external names. |
| 958 |
run_namespace : dict |
| 959 |
A namespace (mapping from strings to objects), as provided as an |
| 960 |
argument to the `Network.run` function or returned by |
| 961 |
`get_local_namespace`. |
| 962 |
user_identifier : bool, optional |
| 963 |
Whether this is an identifier that was used by the user (and not |
| 964 |
something automatically generated that the user might not even |
| 965 |
know about). Will be used to determine whether to display a |
| 966 |
warning in the case of namespace clashes. Defaults to ``True``. |
| 967 |
internal_variable : `Variable`, optional |
| 968 |
The internal variable object that corresponds to this name (if any). |
| 969 |
This is used to give warnings if it also corresponds to a variable |
| 970 |
from an external namespace. |
| 971 |
""" |
| 972 |
# We save tuples of (namespace description, referred object) to |
| 973 |
# give meaningful warnings in case of duplicate definitions |
| 974 |
matches = [] |
| 975 |
|
| 976 |
namespaces = OrderedDict() |
| 977 |
# Default namespaces (units and functions) |
| 978 |
namespaces["constants"] = DEFAULT_CONSTANTS |
| 979 |
namespaces["units"] = DEFAULT_UNITS |
| 980 |
namespaces["functions"] = DEFAULT_FUNCTIONS |
| 981 |
if getattr(self, "namespace", None) is not None: |
| 982 |
namespaces["group-specific"] = self.namespace |
| 983 |
|
| 984 |
# explicit or implicit run namespace |
| 985 |
namespaces["run"] = run_namespace |
| 986 |
|
| 987 |
for description, namespace in namespaces.items(): |
| 988 |
if identifier in namespace: |
| 989 |
match = namespace[identifier] |
| 990 |
if ( |
| 991 |
isinstance( |
| 992 |
match, |
| 993 |
(numbers.Number, np.ndarray, np.generic, Function, Variable), |
| 994 |
) |
| 995 |
) or ( |
| 996 |
inspect.isfunction(match) |
| 997 |
and hasattr(match, "_arg_units") |
| 998 |
and hasattr(match, "_return_unit") |
| 999 |
): |
| 1000 |
matches.append((description, match)) |
| 1001 |
|
| 1002 |
if len(matches) == 0: |
| 1003 |
# No match at all |
| 1004 |
if internal_variable is not None: |
| 1005 |
return None |
| 1006 |
else: |
| 1007 |
# Give a more detailed explanation for the lastupdate variable |
| 1008 |
# that was removed with PR #1003 |
| 1009 |
if identifier == "lastupdate": |
| 1010 |
error_msg = ( |
| 1011 |
'The identifier "lastupdate" could not be ' |
| 1012 |
"resolved. Note that this variable is only " |
| 1013 |
"automatically defined for models with " |
| 1014 |
"event-driven synapses. You can define it " |
| 1015 |
'manually by adding "lastupdate : second" to ' |
| 1016 |
'the equations and setting "lastupdate = t" ' |
| 1017 |
"at the end of your on_pre and/or on_post " |
| 1018 |
"statements." |
| 1019 |
) |
| 1020 |
else: |
| 1021 |
error_msg = f'The identifier "{identifier}" could not be resolved.' |
| 1022 |
raise KeyError(error_msg) |
| 1023 |
|
| 1024 |
elif len(matches) > 1: |
| 1025 |
# Possibly, all matches refer to the same object |
| 1026 |
first_obj = matches[0][1] |
| 1027 |
found_mismatch = False |
| 1028 |
for m in matches: |
| 1029 |
if _same_value(m[1], first_obj): |
| 1030 |
continue |
| 1031 |
if _same_function(m[1], first_obj): |
| 1032 |
continue |
| 1033 |
try: |
| 1034 |
proxy = weakref.proxy(first_obj) |
| 1035 |
if m[1] is proxy: |
| 1036 |
continue |
| 1037 |
except TypeError: |
| 1038 |
pass |
| 1039 |
|
| 1040 |
# Found a mismatch |
| 1041 |
found_mismatch = True |
| 1042 |
break |
| 1043 |
|
| 1044 |
if found_mismatch and user_identifier and internal_variable is None: |
| 1045 |
_conflict_warning( |
| 1046 |
'The name "%s" refers to different objects ' |
| 1047 |
"in different namespaces used for resolving " |
| 1048 |
'names in the context of group "%s". ' |
| 1049 |
"Will use the object from the %s namespace " |
| 1050 |
"with the value %s," |
| 1051 |
% ( |
| 1052 |
identifier, |
| 1053 |
getattr(self, "name", "<unknown>"), |
| 1054 |
matches[0][0], |
| 1055 |
_display_value(first_obj), |
| 1056 |
), |
| 1057 |
matches[1:], |
| 1058 |
) |
| 1059 |
|
| 1060 |
if internal_variable is not None and user_identifier: |
| 1061 |
# Filter out matches that are identical (a typical case being an |
| 1062 |
# externally defined "N" with the the number of neurons and a later |
| 1063 |
# use of "N" in an expression (which refers to the internal variable |
| 1064 |
# storing the number of neurons in the group) |
| 1065 |
if isinstance(internal_variable, Constant): |
| 1066 |
filtered_matches = [] |
| 1067 |
for match in matches: |
| 1068 |
if not _same_value(match[1], internal_variable): |
| 1069 |
filtered_matches.append(match) |
| 1070 |
else: |
| 1071 |
filtered_matches = matches |
| 1072 |
if len(filtered_matches) == 0: |
| 1073 |
pass # Nothing to warn about |
| 1074 |
else: |
| 1075 |
warning_message = ( |
| 1076 |
f"'{identifier}' is an internal variable of group " |
| 1077 |
f"'{self.name}', but also exists in the " |
| 1078 |
) |
| 1079 |
if len(matches) == 1: |
| 1080 |
namespace = filtered_matches[0][0] |
| 1081 |
value = _display_value(filtered_matches[0][1]) |
| 1082 |
warning_message += f"{namespace} namespace with the value {value}. " |
| 1083 |
else: |
| 1084 |
namespaces_list = " ,".join(match[0] for match in filtered_matches) |
| 1085 |
warning_message += f"following namespaces: {namespaces_list}. " |
| 1086 |
warning_message += "The internal variable will be used." |
| 1087 |
logger.warn( |
| 1088 |
warning_message, "Group.resolve.resolution_conflict", once=True |
| 1089 |
) |
| 1090 |
|
| 1091 |
if internal_variable is not None: |
| 1092 |
return None # We were only interested in the warnings above |
| 1093 |
|
| 1094 |
# use the first match (according to resolution order) |
| 1095 |
resolved = matches[0][1] |
| 1096 |
|
| 1097 |
# Replace pure Python functions by a Functions object |
| 1098 |
if callable(resolved) and not isinstance(resolved, Function): |
| 1099 |
resolved = Function( |
| 1100 |
resolved, |
| 1101 |
arg_units=getattr(resolved, "_arg_units", None), |
| 1102 |
arg_names=getattr(resolved, "_arg_names", None), |
| 1103 |
return_unit=getattr(resolved, "_return_unit", None), |
| 1104 |
stateless=getattr(resolved, "stateless", False), |
| 1105 |
) |
| 1106 |
|
| 1107 |
if not isinstance(resolved, (Function, Variable)): |
| 1108 |
# Wrap the value in a Constant object |
| 1109 |
dimensions = getattr(resolved, "dim", DIMENSIONLESS) |
| 1110 |
value = np.asarray(resolved) |
| 1111 |
if value.shape != (): |
| 1112 |
raise KeyError( |
| 1113 |
f"Variable {identifier} was found in the namespace, but is not a" |
| 1114 |
" scalar value" |
| 1115 |
) |
| 1116 |
resolved = Constant(identifier, dimensions=dimensions, value=value) |
| 1117 |
|
| 1118 |
return resolved |
| 1119 |
|
| 1120 |
def runner(self, *args, **kwds): |
| 1121 |
raise AttributeError("The 'runner' method has been renamed to 'run_regularly'.") |
| 1122 |
|
| 1123 |
def custom_operation(self, *args, **kwds): |
| 1124 |
raise AttributeError( |
| 1125 |
"The 'custom_operation' method has been renamed to 'run_regularly'." |
| 1126 |
) |
| 1127 |
|
| 1128 |
def run_regularly( |
| 1129 |
self, |
| 1130 |
code, |
| 1131 |
dt=None, |
| 1132 |
clock=None, |
| 1133 |
when="start", |
| 1134 |
order=0, |
| 1135 |
name=None, |
| 1136 |
codeobj_class=None, |
| 1137 |
): |
| 1138 |
""" |
| 1139 |
Run abstract code in the group's namespace. The created `CodeRunner` |
| 1140 |
object will be automatically added to the group, it therefore does not |
| 1141 |
need to be added to the network manually. However, a reference to the |
| 1142 |
object will be returned, which can be used to later remove it from the |
| 1143 |
group or to set it to inactive. |
| 1144 |
|
| 1145 |
Parameters |
| 1146 |
---------- |
| 1147 |
code : str |
| 1148 |
The abstract code to run. |
| 1149 |
dt : `Quantity`, optional |
| 1150 |
The time step to use for this custom operation. Cannot be combined |
| 1151 |
with the `clock` argument. |
| 1152 |
clock : `Clock`, optional |
| 1153 |
The update clock to use for this operation. If neither a clock nor |
| 1154 |
the `dt` argument is specified, defaults to the clock of the group. |
| 1155 |
when : str, optional |
| 1156 |
When to run within a time step, defaults to the ``'start'`` slot. |
| 1157 |
See :ref:`scheduling` for possible values. |
| 1158 |
name : str, optional |
| 1159 |
A unique name, if non is given the name of the group appended with |
| 1160 |
'run_regularly', 'run_regularly_1', etc. will be used. If a |
| 1161 |
name is given explicitly, it will be used as given (i.e. the group |
| 1162 |
name will not be prepended automatically). |
| 1163 |
codeobj_class : class, optional |
| 1164 |
The `CodeObject` class to run code with. If not specified, defaults |
| 1165 |
to the `group`'s ``codeobj_class`` attribute. |
| 1166 |
|
| 1167 |
Returns |
| 1168 |
------- |
| 1169 |
obj : `CodeRunner` |
| 1170 |
A reference to the object that will be run. |
| 1171 |
""" |
| 1172 |
from brian2.core.clocks import Clock # Avoid circular import |
| 1173 |
|
| 1174 |
if name is None: |
| 1175 |
names = [o.name for o in self.contained_objects] |
| 1176 |
name = find_name(f"{self.name}_run_regularly*", names) |
| 1177 |
|
| 1178 |
if dt is None and clock is None: |
| 1179 |
clock = self._clock |
| 1180 |
elif clock is None: |
| 1181 |
clock = Clock(dt=dt, name=f"{name}_clock*") |
| 1182 |
|
| 1183 |
return self.run_on_clock(code, clock, when, order, name, codeobj_class) |
| 1184 |
|
| 1185 |
def run_on_clock( |
| 1186 |
self, |
| 1187 |
code, |
| 1188 |
clock=None, |
| 1189 |
when="start", |
| 1190 |
order=0, |
| 1191 |
name=None, |
| 1192 |
codeobj_class=None, |
| 1193 |
): |
| 1194 |
""" |
| 1195 |
This method is used by `run_regularly` and `run_at` to register operations |
| 1196 |
that are executed at times determined by a user-supplied or internally generated `Clock`. |
| 1197 |
The resulting `CodeRunner` is automatically added to the group. |
| 1198 |
|
| 1199 |
Parameters |
| 1200 |
---------- |
| 1201 |
code : str |
| 1202 |
The abstract code to run. |
| 1203 |
clock : `Clock`, optional |
| 1204 |
The update clock to use for this operation. If neither a clock nor |
| 1205 |
the `dt` argument is specified, defaults to the clock of the group. |
| 1206 |
when : str, optional |
| 1207 |
When to run within a time step, defaults to the ``'start'`` slot. |
| 1208 |
See :ref:`scheduling` for possible values. |
| 1209 |
name : str, optional |
| 1210 |
A unique name, if non is given the name of the group appended with |
| 1211 |
'run_custom_clock', 'run_custom_clock_1', etc. will be used. If a |
| 1212 |
name is given explicitly, it will be used as given (i.e. the group |
| 1213 |
name will not be prepended automatically). |
| 1214 |
codeobj_class : class, optional |
| 1215 |
The `CodeObject` class to run code with. If not specified, defaults |
| 1216 |
to the `group`'s ``codeobj_class`` attribute. |
| 1217 |
|
| 1218 |
Returns |
| 1219 |
------- |
| 1220 |
obj : `CodeRunner` |
| 1221 |
A reference to the object that will be run. |
| 1222 |
""" |
| 1223 |
if name is None: |
| 1224 |
names = [o.name for o in self.contained_objects] |
| 1225 |
name = find_name(f"{self.name}_run_custom*", names) |
| 1226 |
|
| 1227 |
# Subgroups are normally not included in their parent's |
| 1228 |
# contained_objects list, since there's no need to include them in the |
| 1229 |
# network (they don't perform any computation on their own). However, |
| 1230 |
# if a subgroup declares a `run_regularly` operation, then we want to |
| 1231 |
# include this operation automatically, i.e. with the parent group |
| 1232 |
# (adding just the run_regularly operation to the parent group's |
| 1233 |
# contained objects would no be enough, since the CodeObject needs a |
| 1234 |
# reference to the group providing the context for the operation, i.e. |
| 1235 |
# the subgroup instead of the parent group. See github issue #922 |
| 1236 |
source_group = getattr(self, "source", None) |
| 1237 |
if source_group is not None: |
| 1238 |
if self not in source_group.contained_objects: |
| 1239 |
source_group.contained_objects.append(self) |
| 1240 |
|
| 1241 |
runner = CodeRunner( |
| 1242 |
self, |
| 1243 |
"stateupdate", |
| 1244 |
code=code, |
| 1245 |
name=name, |
| 1246 |
clock=clock, |
| 1247 |
when=when, |
| 1248 |
order=order, |
| 1249 |
codeobj_class=codeobj_class, |
| 1250 |
) |
| 1251 |
self.contained_objects.append(runner) |
| 1252 |
return runner |
| 1253 |
|
| 1254 |
def run_at( |
| 1255 |
self, |
| 1256 |
code, |
| 1257 |
times, |
| 1258 |
when="start", |
| 1259 |
order=0, |
| 1260 |
name=None, |
| 1261 |
codeobj_class=None, |
| 1262 |
): |
| 1263 |
""" |
| 1264 |
Run abstract code in the group's namespace. The created `CodeRunner` |
| 1265 |
object will be automatically added to the group, it therefore does not |
| 1266 |
need to be added to the network manually. However, a reference to the |
| 1267 |
object will be returned, which can be used to later remove it from the |
| 1268 |
group or to set it to inactive. |
| 1269 |
|
| 1270 |
Parameters |
| 1271 |
---------- |
| 1272 |
code : str |
| 1273 |
The abstract code to run. |
| 1274 |
times : array-like |
| 1275 |
The specific simulation times at which to execute the code. |
| 1276 |
when : str, optional |
| 1277 |
When to run within a time step, defaults to the ``'start'`` slot. |
| 1278 |
See :ref:`scheduling` for possible values. |
| 1279 |
name : str, optional |
| 1280 |
A unique name, if non is given the name of the group appended with |
| 1281 |
'run_at', 'run_at_1', etc. will be used. If a |
| 1282 |
name is given explicitly, it will be used as given (i.e. the group |
| 1283 |
name will not be prepended automatically). |
| 1284 |
codeobj_class : class, optional |
| 1285 |
The `CodeObject` class to run code with. If not specified, defaults |
| 1286 |
to the `group`'s ``codeobj_class`` attribute. |
| 1287 |
|
| 1288 |
Returns |
| 1289 |
------- |
| 1290 |
obj : `CodeRunner` |
| 1291 |
A reference to the object that will be run. |
| 1292 |
""" |
| 1293 |
if name is None: |
| 1294 |
names = [o.name for o in self.contained_objects] |
| 1295 |
name = find_name(f"{self.name}_run_at*", names) |
| 1296 |
from brian2.core.clocks import EventClock |
| 1297 |
|
| 1298 |
clock = EventClock(times, name=f"{name}_eventclock*") |
| 1299 |
return self.run_on_clock(code, clock, when, order, name, codeobj_class) |
| 1300 |
|
| 1301 |
def _check_for_invalid_states(self): |
| 1302 |
""" |
| 1303 |
Checks if any state variables updated by differential equations have |
| 1304 |
invalid values, and logs a warning if so. |
| 1305 |
""" |
| 1306 |
equations = getattr(self, "equations", None) |
| 1307 |
if not isinstance(equations, Equations): |
| 1308 |
return |
| 1309 |
for varname in equations.diff_eq_names: |
| 1310 |
self._check_for_invalid_values( |
| 1311 |
varname, self.state(varname, use_units=False) |
| 1312 |
) |
| 1313 |
|
| 1314 |
def _check_for_invalid_values(self, k, v): |
| 1315 |
""" |
| 1316 |
Checks if variable named k value v has invalid values, and logs a |
| 1317 |
warning if so. |
| 1318 |
""" |
| 1319 |
v = np.asarray(v) |
| 1320 |
if np.isnan(v).any() or (np.abs(v) > 1e50).any(): |
| 1321 |
logger.warn( |
| 1322 |
f"{self.name}'s variable '{k}' has NaN, very large values, " |
| 1323 |
"or encountered an error in numerical integration. " |
| 1324 |
"This is usually a sign that an unstable or invalid " |
| 1325 |
"integration method was " |
| 1326 |
"chosen.", |
| 1327 |
name_suffix="invalid_values", |
| 1328 |
once=True, |
| 1329 |
) |
| 1330 |
|
| 1331 |
|
| 1332 |
class CodeRunner(BrianObject): |
| 1333 |
""" |
| 1334 |
A "code runner" that runs a `CodeObject` every timestep and keeps a |
| 1335 |
reference to the `Group`. Used in `NeuronGroup` for `Thresholder`, |
| 1336 |
`Resetter` and `StateUpdater`. |
| 1337 |
|
| 1338 |
On creation, we try to run the before_run method with an empty additional |
| 1339 |
namespace (see `Network.before_run`). If the namespace is already complete |
| 1340 |
this might catch unit mismatches. |
| 1341 |
|
| 1342 |
Parameters |
| 1343 |
---------- |
| 1344 |
group : `Group` |
| 1345 |
The group to which this object belongs. |
| 1346 |
template : `Template` |
| 1347 |
The template that should be used for code generation |
| 1348 |
code : str, optional |
| 1349 |
The abstract code that should be executed every time step. The |
| 1350 |
`update_abstract_code` method might generate this code dynamically |
| 1351 |
before every run instead. |
| 1352 |
dt : `Quantity`, optional |
| 1353 |
The time step to be used for the simulation. Cannot be combined with |
| 1354 |
the `clock` argument. |
| 1355 |
user_code : str, optional |
| 1356 |
The abstract code as specified by the user, i.e. without any additions |
| 1357 |
of internal code that the user not necessarily knows about. This will |
| 1358 |
be used for warnings and error messages. |
| 1359 |
clock : `Clock`, optional |
| 1360 |
The update clock to be used. If neither a clock, nor the `dt` argument |
| 1361 |
is specified, the `defaultclock` will be used. |
| 1362 |
when : str, optional |
| 1363 |
In which scheduling slot to execute the operation during a time step. |
| 1364 |
Defaults to ``'start'``. See :ref:`scheduling` for possible values. |
| 1365 |
order : int, optional |
| 1366 |
The priority of this operation for operations occurring at the same time |
| 1367 |
step and in the same scheduling slot. Defaults to 0. |
| 1368 |
name : str, optional |
| 1369 |
The name for this object. |
| 1370 |
check_units : bool, optional |
| 1371 |
Whether the units should be checked for consistency before a run. Is |
| 1372 |
activated (``True``) by default but should be switched off for state |
| 1373 |
updaters (units are already checked for the equations and the generated |
| 1374 |
abstract code might have already replaced variables with their unit-less |
| 1375 |
values) |
| 1376 |
template_kwds : dict, optional |
| 1377 |
A dictionary of additional information that is passed to the template. |
| 1378 |
needed_variables: list of str, optional |
| 1379 |
A list of variables that are neither present in the abstract code, nor |
| 1380 |
in the ``USES_VARIABLES`` statement in the template. This is only |
| 1381 |
rarely necessary, an example being a `StateMonitor` where the |
| 1382 |
names of the variables are neither known to the template nor included |
| 1383 |
in the abstract code statements. |
| 1384 |
override_conditional_write: list of str, optional |
| 1385 |
A list of variable names which are used as conditions (e.g. for |
| 1386 |
refractoriness) which should be ignored. |
| 1387 |
codeobj_class : class, optional |
| 1388 |
The `CodeObject` class to run code with. If not specified, defaults to |
| 1389 |
the `group`'s ``codeobj_class`` attribute. |
| 1390 |
generate_empty_code : bool, optional |
| 1391 |
Whether to generate a `CodeObject` if there is no abstract code to |
| 1392 |
execute. Defaults to ``True`` but should be switched off e.g. for a |
| 1393 |
`StateUpdater` when there is nothing to do. |
| 1394 |
""" |
| 1395 |
|
| 1396 |
add_to_magic_network = True |
| 1397 |
invalidates_magic_network = True |
| 1398 |
|
| 1399 |
def __init__( |
| 1400 |
self, |
| 1401 |
group, |
| 1402 |
template, |
| 1403 |
code="", |
| 1404 |
user_code=None, |
| 1405 |
dt=None, |
| 1406 |
clock=None, |
| 1407 |
when="start", |
| 1408 |
order=0, |
| 1409 |
name="coderunner*", |
| 1410 |
check_units=True, |
| 1411 |
template_kwds=None, |
| 1412 |
needed_variables=None, |
| 1413 |
override_conditional_write=None, |
| 1414 |
codeobj_class=None, |
| 1415 |
generate_empty_code=True, |
| 1416 |
): |
| 1417 |
BrianObject.__init__( |
| 1418 |
self, clock=clock, dt=dt, when=when, order=order, name=name |
| 1419 |
) |
| 1420 |
self.group = weakproxy_with_fallback(group) |
| 1421 |
self.template = template |
| 1422 |
self.user_code = user_code |
| 1423 |
self.abstract_code = code |
| 1424 |
self.check_units = check_units |
| 1425 |
if needed_variables is None: |
| 1426 |
needed_variables = [] |
| 1427 |
self.needed_variables = needed_variables |
| 1428 |
self.template_kwds = template_kwds |
| 1429 |
self.override_conditional_write = override_conditional_write |
| 1430 |
if codeobj_class is None: |
| 1431 |
codeobj_class = group.codeobj_class |
| 1432 |
self.codeobj_class = codeobj_class |
| 1433 |
self.generate_empty_code = generate_empty_code |
| 1434 |
self.codeobj = None |
| 1435 |
|
| 1436 |
def __getstate__(self): |
| 1437 |
state = self.__dict__.copy() |
| 1438 |
state["group"] = state["group"].__repr__.__self__ |
| 1439 |
return state |
| 1440 |
|
| 1441 |
def __setstate__(self, state): |
| 1442 |
state["group"] = weakproxy_with_fallback(state["group"]) |
| 1443 |
self.__dict__ = state |
| 1444 |
|
| 1445 |
def update_abstract_code(self, run_namespace): |
| 1446 |
""" |
| 1447 |
Update the abstract code for the code object. Will be called in |
| 1448 |
`before_run` and should update the `CodeRunner.abstract_code` |
| 1449 |
attribute. |
| 1450 |
|
| 1451 |
Does nothing by default. |
| 1452 |
""" |
| 1453 |
pass |
| 1454 |
|
| 1455 |
def create_default_code_object(self, run_namespace): |
| 1456 |
self.update_abstract_code(run_namespace=run_namespace) |
| 1457 |
# If the CodeRunner has variables, add them |
| 1458 |
if hasattr(self, "variables"): |
| 1459 |
additional_variables = self.variables |
| 1460 |
else: |
| 1461 |
additional_variables = None |
| 1462 |
|
| 1463 |
if not self.generate_empty_code and len(self.abstract_code) == 0: |
| 1464 |
self.codeobj = None |
| 1465 |
else: |
| 1466 |
self.codeobj = create_runner_codeobj( |
| 1467 |
group=self.group, |
| 1468 |
code=self.abstract_code, |
| 1469 |
user_code=self.user_code, |
| 1470 |
template_name=self.template, |
| 1471 |
name=f"{self.name}_codeobject*", |
| 1472 |
check_units=self.check_units, |
| 1473 |
additional_variables=additional_variables, |
| 1474 |
needed_variables=self.needed_variables, |
| 1475 |
run_namespace=run_namespace, |
| 1476 |
template_kwds=self.template_kwds, |
| 1477 |
override_conditional_write=self.override_conditional_write, |
| 1478 |
codeobj_class=self.codeobj_class, |
| 1479 |
) |
| 1480 |
return self.codeobj |
| 1481 |
|
| 1482 |
def create_code_objects(self, run_namespace): |
| 1483 |
# By default, we only have one code object for each CodeRunner. |
| 1484 |
# Overwrite this function to use more than one. |
| 1485 |
code_object = self.create_default_code_object(run_namespace) |
| 1486 |
if code_object: |
| 1487 |
self.code_objects[:] = [weakref.proxy(code_object)] |
| 1488 |
else: |
| 1489 |
self.code_objects[:] = [] |
| 1490 |
|
| 1491 |
def before_run(self, run_namespace): |
| 1492 |
self.create_code_objects(run_namespace) |
| 1493 |
super().before_run(run_namespace) |