| 1 |
""" |
| 2 |
Classes used to specify the type of a function, variable or common |
| 3 |
sub-expression. |
| 4 |
""" |
| 5 |
|
| 6 |
import collections |
| 7 |
import functools |
| 8 |
import numbers |
| 9 |
from collections.abc import Mapping |
| 10 |
|
| 11 |
import numpy as np |
| 12 |
|
| 13 |
from brian2.units.fundamentalunits import ( |
| 14 |
DIMENSIONLESS, |
| 15 |
Dimension, |
| 16 |
Quantity, |
| 17 |
fail_for_dimension_mismatch, |
| 18 |
get_unit, |
| 19 |
get_unit_for_display, |
| 20 |
) |
| 21 |
from brian2.utils.caching import CacheKey |
| 22 |
from brian2.utils.logger import get_logger |
| 23 |
from brian2.utils.stringtools import get_identifiers, word_substitute |
| 24 |
|
| 25 |
from .base import device_override, weakproxy_with_fallback |
| 26 |
from .preferences import prefs |
| 27 |
|
| 28 |
__all__ = [ |
| 29 |
"Variable", |
| 30 |
"Constant", |
| 31 |
"ArrayVariable", |
| 32 |
"DynamicArrayVariable", |
| 33 |
"Subexpression", |
| 34 |
"AuxiliaryVariable", |
| 35 |
"VariableView", |
| 36 |
"Variables", |
| 37 |
"LinkedVariable", |
| 38 |
"linked_var", |
| 39 |
] |
| 40 |
|
| 41 |
|
| 42 |
logger = get_logger(__name__) |
| 43 |
|
| 44 |
|
| 45 |
def get_dtype(obj): |
| 46 |
""" |
| 47 |
Helper function to return the `numpy.dtype` of an arbitrary object. |
| 48 |
|
| 49 |
Parameters |
| 50 |
---------- |
| 51 |
obj : object |
| 52 |
Any object (but typically some kind of number or array). |
| 53 |
|
| 54 |
Returns |
| 55 |
------- |
| 56 |
dtype : `numpy.dtype` |
| 57 |
The type of the given object. |
| 58 |
""" |
| 59 |
if hasattr(obj, "dtype"): |
| 60 |
return obj.dtype |
| 61 |
else: |
| 62 |
return np.dtype(type(obj)) |
| 63 |
|
| 64 |
|
| 65 |
def get_dtype_str(val): |
| 66 |
""" |
| 67 |
Returns canonical string representation of the dtype of a value or dtype |
| 68 |
|
| 69 |
Returns |
| 70 |
------- |
| 71 |
|
| 72 |
dtype_str : str |
| 73 |
The numpy dtype name |
| 74 |
""" |
| 75 |
if isinstance(val, np.dtype): |
| 76 |
return val.name |
| 77 |
if isinstance(val, type): |
| 78 |
return get_dtype_str(val()) |
| 79 |
|
| 80 |
is_bool = val is True or val is False or val is np.True_ or val is np.False_ |
| 81 |
if is_bool: |
| 82 |
return "bool" |
| 83 |
if hasattr(val, "dtype"): |
| 84 |
return get_dtype_str(val.dtype) |
| 85 |
if isinstance(val, numbers.Number): |
| 86 |
return get_dtype_str(np.array(val).dtype) |
| 87 |
|
| 88 |
return f"unknown[{str(val)}, {val.__class__.__name__}]" |
| 89 |
|
| 90 |
|
| 91 |
def variables_by_owner(variables, owner): |
| 92 |
owner_name = getattr(owner, "name", None) |
| 93 |
return { |
| 94 |
varname: var |
| 95 |
for varname, var in variables.items() |
| 96 |
if getattr(var.owner, "name", None) is owner_name |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
class Variable(CacheKey): |
| 101 |
r""" |
| 102 |
An object providing information about model variables (including implicit |
| 103 |
variables such as ``t`` or ``xi``). This class should never be |
| 104 |
instantiated outside of testing code, use one of its subclasses instead. |
| 105 |
|
| 106 |
Parameters |
| 107 |
---------- |
| 108 |
name : 'str' |
| 109 |
The name of the variable. Note that this refers to the *original* |
| 110 |
name in the owning group. The same variable may be known under other |
| 111 |
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is |
| 112 |
known as ``v_post`` in a `Synapse` connecting to the group). |
| 113 |
dimensions : `Dimension`, optional |
| 114 |
The physical dimensions of the variable. |
| 115 |
owner : `Nameable`, optional |
| 116 |
The object that "owns" this variable, e.g. the `NeuronGroup` or |
| 117 |
`Synapses` object that declares the variable in its model equations. |
| 118 |
Defaults to ``None`` (the value used for `Variable` objects without an |
| 119 |
owner, e.g. external `Constant`\ s). |
| 120 |
dtype : `dtype`, optional |
| 121 |
The dtype used for storing the variable. Defaults to the preference |
| 122 |
`core.default_scalar.dtype`. |
| 123 |
scalar : bool, optional |
| 124 |
Whether the variable is a scalar value (``True``) or vector-valued, e.g. |
| 125 |
defined for every neuron (``False``). Defaults to ``False``. |
| 126 |
constant: bool, optional |
| 127 |
Whether the value of this variable can change during a run. Defaults |
| 128 |
to ``False``. |
| 129 |
read_only : bool, optional |
| 130 |
Whether this is a read-only variable, i.e. a variable that is set |
| 131 |
internally and cannot be changed by the user (this is used for example |
| 132 |
for the variable ``N``, the number of neurons in a group). Defaults |
| 133 |
to ``False``. |
| 134 |
array : bool, optional |
| 135 |
Whether this variable is an array. Allows for simpler check than testing |
| 136 |
``isinstance(var, ArrayVariable)``. Defaults to ``False``. |
| 137 |
""" |
| 138 |
|
| 139 |
_cache_irrelevant_attributes = {"owner"} |
| 140 |
|
| 141 |
def __init__( |
| 142 |
self, |
| 143 |
name, |
| 144 |
dimensions=DIMENSIONLESS, |
| 145 |
owner=None, |
| 146 |
dtype=None, |
| 147 |
scalar=False, |
| 148 |
constant=False, |
| 149 |
read_only=False, |
| 150 |
dynamic=False, |
| 151 |
array=False, |
| 152 |
): |
| 153 |
assert isinstance(dimensions, Dimension) |
| 154 |
|
| 155 |
#: The variable's dimensions. |
| 156 |
self.dim = dimensions |
| 157 |
|
| 158 |
#: The variable's name. |
| 159 |
self.name = name |
| 160 |
|
| 161 |
#: The `Group` to which this variable belongs. |
| 162 |
self.owner = weakproxy_with_fallback(owner) if owner is not None else None |
| 163 |
|
| 164 |
#: The dtype used for storing the variable. |
| 165 |
self.dtype = dtype |
| 166 |
if dtype is None: |
| 167 |
self.dtype = prefs.core.default_float_dtype |
| 168 |
|
| 169 |
if self.is_boolean: |
| 170 |
if dimensions is not DIMENSIONLESS: |
| 171 |
raise ValueError("Boolean variables can only be dimensionless") |
| 172 |
|
| 173 |
#: Whether the variable is a scalar |
| 174 |
self.scalar = scalar |
| 175 |
|
| 176 |
#: Whether the variable is constant during a run |
| 177 |
self.constant = constant |
| 178 |
|
| 179 |
#: Whether the variable is read-only |
| 180 |
self.read_only = read_only |
| 181 |
|
| 182 |
#: Whether the variable is dynamically sized (only for non-scalars) |
| 183 |
self.dynamic = dynamic |
| 184 |
|
| 185 |
#: Whether the variable is an array |
| 186 |
self.array = array |
| 187 |
|
| 188 |
def __getstate__(self): |
| 189 |
state = self.__dict__.copy() |
| 190 |
state["owner"] = state["owner"].__repr__.__self__ # replace proxy |
| 191 |
return state |
| 192 |
|
| 193 |
def __setstate__(self, state): |
| 194 |
state["owner"] = weakproxy_with_fallback(state["owner"]) |
| 195 |
self.__dict__ = state |
| 196 |
|
| 197 |
@property |
| 198 |
def is_boolean(self): |
| 199 |
return np.issubdtype(self.dtype, np.bool_) |
| 200 |
|
| 201 |
@property |
| 202 |
def is_integer(self): |
| 203 |
return np.issubdtype(self.dtype, np.signedinteger) |
| 204 |
|
| 205 |
@property |
| 206 |
def dtype_str(self): |
| 207 |
""" |
| 208 |
String representation of the numpy dtype |
| 209 |
""" |
| 210 |
return get_dtype_str(self) |
| 211 |
|
| 212 |
@property |
| 213 |
def unit(self): |
| 214 |
""" |
| 215 |
The `Unit` of this variable |
| 216 |
""" |
| 217 |
return get_unit(self.dim) |
| 218 |
|
| 219 |
def get_value(self): |
| 220 |
""" |
| 221 |
Return the value associated with the variable (without units). This |
| 222 |
is the way variables are accessed in generated code. |
| 223 |
""" |
| 224 |
raise TypeError(f"Cannot get value for variable {self}") |
| 225 |
|
| 226 |
def set_value(self, value): |
| 227 |
""" |
| 228 |
Set the value associated with the variable. |
| 229 |
""" |
| 230 |
raise TypeError(f"Cannot set value for variable {self}") |
| 231 |
|
| 232 |
def get_value_with_unit(self): |
| 233 |
""" |
| 234 |
Return the value associated with the variable (with units). |
| 235 |
""" |
| 236 |
return Quantity(self.get_value(), self.dim) |
| 237 |
|
| 238 |
def get_addressable_value(self, name, group): |
| 239 |
""" |
| 240 |
Get the value (without units) of this variable in a form that can be |
| 241 |
indexed in the context of a group. For example, if a |
| 242 |
postsynaptic variable ``x`` is accessed in a synapse ``S`` as |
| 243 |
``S.x_post``, the synaptic indexing scheme can be used. |
| 244 |
|
| 245 |
Parameters |
| 246 |
---------- |
| 247 |
name : str |
| 248 |
The name of the variable |
| 249 |
group : `Group` |
| 250 |
The group providing the context for the indexing. Note that this |
| 251 |
`group` is not necessarily the same as `Variable.owner`: a variable |
| 252 |
owned by a `NeuronGroup` can be indexed in a different way if |
| 253 |
accessed via a `Synapses` object. |
| 254 |
|
| 255 |
Returns |
| 256 |
------- |
| 257 |
variable : object |
| 258 |
The variable in an indexable form (without units). |
| 259 |
""" |
| 260 |
return self.get_value() |
| 261 |
|
| 262 |
def get_addressable_value_with_unit(self, name, group): |
| 263 |
""" |
| 264 |
Get the value (with units) of this variable in a form that can be |
| 265 |
indexed in the context of a group. For example, if a postsynaptic |
| 266 |
variable ``x`` is accessed in a synapse ``S`` as ``S.x_post``, the |
| 267 |
synaptic indexing scheme can be used. |
| 268 |
|
| 269 |
Parameters |
| 270 |
---------- |
| 271 |
name : str |
| 272 |
The name of the variable |
| 273 |
group : `Group` |
| 274 |
The group providing the context for the indexing. Note that this |
| 275 |
`group` is not necessarily the same as `Variable.owner`: a variable |
| 276 |
owned by a `NeuronGroup` can be indexed in a different way if |
| 277 |
accessed via a `Synapses` object. |
| 278 |
|
| 279 |
Returns |
| 280 |
------- |
| 281 |
variable : object |
| 282 |
The variable in an indexable form (with units). |
| 283 |
""" |
| 284 |
return self.get_value_with_unit() |
| 285 |
|
| 286 |
def get_len(self): |
| 287 |
""" |
| 288 |
Get the length of the value associated with the variable or ``0`` for |
| 289 |
a scalar variable. |
| 290 |
""" |
| 291 |
if self.scalar: |
| 292 |
return 0 |
| 293 |
else: |
| 294 |
return len(self.get_value()) |
| 295 |
|
| 296 |
def __len__(self): |
| 297 |
return self.get_len() |
| 298 |
|
| 299 |
def __repr__(self): |
| 300 |
description = ( |
| 301 |
"<{classname}(dimensions={dimensions}, " |
| 302 |
" dtype={dtype}, scalar={scalar}, constant={constant}," |
| 303 |
" read_only={read_only})>" |
| 304 |
) |
| 305 |
return description.format( |
| 306 |
classname=self.__class__.__name__, |
| 307 |
dimensions=repr(self.dim), |
| 308 |
dtype=getattr(self.dtype, "__name__", repr(self.dtype)), |
| 309 |
scalar=repr(self.scalar), |
| 310 |
constant=repr(self.constant), |
| 311 |
read_only=repr(self.read_only), |
| 312 |
) |
| 313 |
|
| 314 |
|
| 315 |
# ------------------------------------------------------------------------------ |
| 316 |
# Concrete classes derived from `Variable` -- these are the only ones ever |
| 317 |
# instantiated. |
| 318 |
# ------------------------------------------------------------------------------ |
| 319 |
|
| 320 |
|
| 321 |
class Constant(Variable): |
| 322 |
""" |
| 323 |
A scalar constant (e.g. the number of neurons ``N``). Information such as |
| 324 |
the dtype or whether this variable is a boolean are directly derived from |
| 325 |
the `value`. Most of the time `Variables.add_constant` should be used |
| 326 |
instead of instantiating this class directly. |
| 327 |
|
| 328 |
Parameters |
| 329 |
---------- |
| 330 |
name : str |
| 331 |
The name of the variable |
| 332 |
dimensions : `Dimension`, optional |
| 333 |
The physical dimensions of the variable. Note that the variable itself |
| 334 |
(as referenced by value) should never have units attached. |
| 335 |
value: reference to the variable value |
| 336 |
The value of the constant. |
| 337 |
owner : `Nameable`, optional |
| 338 |
The object that "owns" this variable, for constants that belong to a |
| 339 |
specific group, e.g. the ``N`` constant for a `NeuronGroup`. External |
| 340 |
constants will have ``None`` (the default value). |
| 341 |
""" |
| 342 |
|
| 343 |
def __init__(self, name, value, dimensions=DIMENSIONLESS, owner=None): |
| 344 |
# Determine the type of the value |
| 345 |
is_bool = ( |
| 346 |
value is True or value is False or value is np.True_ or value is np.False_ |
| 347 |
) |
| 348 |
|
| 349 |
if is_bool: |
| 350 |
dtype = bool |
| 351 |
else: |
| 352 |
dtype = get_dtype(value) |
| 353 |
|
| 354 |
# Use standard Python types if possible for numpy scalars |
| 355 |
if getattr(value, "shape", None) == () and hasattr(value, "dtype"): |
| 356 |
numpy_type = value.dtype |
| 357 |
if np.can_cast(numpy_type, int): |
| 358 |
value = int(value) |
| 359 |
elif np.can_cast(numpy_type, float): |
| 360 |
value = float(value) |
| 361 |
elif np.can_cast(numpy_type, complex): |
| 362 |
value = complex(value) |
| 363 |
elif value is np.True_: |
| 364 |
value = True |
| 365 |
elif value is np.False_: |
| 366 |
value = False |
| 367 |
|
| 368 |
#: The constant's value |
| 369 |
self.value = value |
| 370 |
|
| 371 |
super().__init__( |
| 372 |
dimensions=dimensions, |
| 373 |
name=name, |
| 374 |
owner=owner, |
| 375 |
dtype=dtype, |
| 376 |
scalar=True, |
| 377 |
constant=True, |
| 378 |
read_only=True, |
| 379 |
) |
| 380 |
|
| 381 |
def get_value(self): |
| 382 |
return self.value |
| 383 |
|
| 384 |
def item(self): |
| 385 |
return self.value |
| 386 |
|
| 387 |
|
| 388 |
class AuxiliaryVariable(Variable): |
| 389 |
""" |
| 390 |
Variable description for an auxiliary variable (most likely one that is |
| 391 |
added automatically to abstract code, e.g. ``_cond`` for a threshold |
| 392 |
condition), specifying its type and unit for code generation. Most of the |
| 393 |
time `Variables.add_auxiliary_variable` should be used instead of |
| 394 |
instantiating this class directly. |
| 395 |
|
| 396 |
Parameters |
| 397 |
---------- |
| 398 |
name : str |
| 399 |
The name of the variable |
| 400 |
dimensions : `Dimension`, optional |
| 401 |
The physical dimensions of the variable. |
| 402 |
dtype : `dtype`, optional |
| 403 |
The dtype used for storing the variable. If none is given, defaults |
| 404 |
to `core.default_float_dtype`. |
| 405 |
scalar : bool, optional |
| 406 |
Whether the variable is a scalar value (``True``) or vector-valued, e.g. |
| 407 |
defined for every neuron (``False``). Defaults to ``False``. |
| 408 |
""" |
| 409 |
|
| 410 |
def __init__(self, name, dimensions=DIMENSIONLESS, dtype=None, scalar=False): |
| 411 |
super().__init__(dimensions=dimensions, name=name, dtype=dtype, scalar=scalar) |
| 412 |
|
| 413 |
def get_value(self): |
| 414 |
raise TypeError( |
| 415 |
f"Cannot get the value for an auxiliary variable ({self.name})." |
| 416 |
) |
| 417 |
|
| 418 |
|
| 419 |
class ArrayVariable(Variable): |
| 420 |
""" |
| 421 |
An object providing information about a model variable stored in an array |
| 422 |
(for example, all state variables). Most of the time `Variables.add_array` |
| 423 |
should be used instead of instantiating this class directly. |
| 424 |
|
| 425 |
Parameters |
| 426 |
---------- |
| 427 |
name : 'str' |
| 428 |
The name of the variable. Note that this refers to the *original* |
| 429 |
name in the owning group. The same variable may be known under other |
| 430 |
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is |
| 431 |
known as ``v_post`` in a `Synapse` connecting to the group). |
| 432 |
dimensions : `Dimension`, optional |
| 433 |
The physical dimensions of the variable |
| 434 |
owner : `Nameable` |
| 435 |
The object that "owns" this variable, e.g. the `NeuronGroup` or |
| 436 |
`Synapses` object that declares the variable in its model equations. |
| 437 |
size : int |
| 438 |
The size of the array |
| 439 |
device : `Device` |
| 440 |
The device responsible for the memory access. |
| 441 |
dtype : `dtype`, optional |
| 442 |
The dtype used for storing the variable. If none is given, defaults |
| 443 |
to `core.default_float_dtype`. |
| 444 |
constant : bool, optional |
| 445 |
Whether the variable's value is constant during a run. |
| 446 |
Defaults to ``False``. |
| 447 |
scalar : bool, optional |
| 448 |
Whether this array is a 1-element array that should be treated like a |
| 449 |
scalar (e.g. for a single delay value across synapses). Defaults to |
| 450 |
``False``. |
| 451 |
read_only : bool, optional |
| 452 |
Whether this is a read-only variable, i.e. a variable that is set |
| 453 |
internally and cannot be changed by the user. Defaults |
| 454 |
to ``False``. |
| 455 |
unique : bool, optional |
| 456 |
Whether the values in this array are all unique. This information is |
| 457 |
only important for variables used as indices and does not have to |
| 458 |
reflect the actual contents of the array but only the possibility of |
| 459 |
non-uniqueness (e.g. synaptic indices are always unique but the |
| 460 |
corresponding pre- and post-synaptic indices are not). Defaults to |
| 461 |
``False``. |
| 462 |
""" |
| 463 |
|
| 464 |
def __init__( |
| 465 |
self, |
| 466 |
name, |
| 467 |
owner, |
| 468 |
size, |
| 469 |
device, |
| 470 |
dimensions=DIMENSIONLESS, |
| 471 |
dtype=None, |
| 472 |
constant=False, |
| 473 |
scalar=False, |
| 474 |
read_only=False, |
| 475 |
dynamic=False, |
| 476 |
unique=False, |
| 477 |
): |
| 478 |
super().__init__( |
| 479 |
dimensions=dimensions, |
| 480 |
name=name, |
| 481 |
owner=owner, |
| 482 |
dtype=dtype, |
| 483 |
scalar=scalar, |
| 484 |
constant=constant, |
| 485 |
read_only=read_only, |
| 486 |
dynamic=dynamic, |
| 487 |
array=True, |
| 488 |
) |
| 489 |
|
| 490 |
#: Wether all values in this arrays are necessarily unique (only |
| 491 |
#: relevant for index variables). |
| 492 |
self.unique = unique |
| 493 |
|
| 494 |
#: The `Device` responsible for memory access. |
| 495 |
self.device = device |
| 496 |
|
| 497 |
#: The size of this variable. |
| 498 |
self.size = size |
| 499 |
|
| 500 |
if scalar and size != 1: |
| 501 |
raise ValueError(f"Scalar variables need to have size 1, not size {size}.") |
| 502 |
|
| 503 |
#: Another variable, on which the write is conditioned (e.g. a variable |
| 504 |
#: denoting the absence of refractoriness) |
| 505 |
self.conditional_write = None |
| 506 |
|
| 507 |
def set_conditional_write(self, var): |
| 508 |
if not var.is_boolean: |
| 509 |
raise TypeError( |
| 510 |
"A variable can only be conditionally writeable " |
| 511 |
f"depending on a boolean variable, '{var.name}' is not " |
| 512 |
"boolean." |
| 513 |
) |
| 514 |
self.conditional_write = var |
| 515 |
|
| 516 |
def get_value(self): |
| 517 |
return self.device.get_value(self) |
| 518 |
|
| 519 |
def item(self): |
| 520 |
if self.size == 1: |
| 521 |
return self.get_value().item() |
| 522 |
else: |
| 523 |
raise ValueError("can only convert an array of size 1 to a Python scalar") |
| 524 |
|
| 525 |
def set_value(self, value): |
| 526 |
self.device.fill_with_array(self, value) |
| 527 |
|
| 528 |
def get_len(self): |
| 529 |
return self.size |
| 530 |
|
| 531 |
def get_addressable_value(self, name, group): |
| 532 |
return VariableView(name=name, variable=self, group=group, dimensions=None) |
| 533 |
|
| 534 |
def get_addressable_value_with_unit(self, name, group): |
| 535 |
return VariableView(name=name, variable=self, group=group, dimensions=self.dim) |
| 536 |
|
| 537 |
|
| 538 |
class DynamicArrayVariable(ArrayVariable): |
| 539 |
""" |
| 540 |
An object providing information about a model variable stored in a dynamic |
| 541 |
array (used in `Synapses`). Most of the time `Variables.add_dynamic_array` |
| 542 |
should be used instead of instantiating this class directly. |
| 543 |
|
| 544 |
Parameters |
| 545 |
---------- |
| 546 |
name : 'str' |
| 547 |
The name of the variable. Note that this refers to the *original* |
| 548 |
name in the owning group. The same variable may be known under other |
| 549 |
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is |
| 550 |
known as ``v_post`` in a `Synapse` connecting to the group). |
| 551 |
dimensions : `Dimension`, optional |
| 552 |
The physical dimensions of the variable. |
| 553 |
owner : `Nameable` |
| 554 |
The object that "owns" this variable, e.g. the `NeuronGroup` or |
| 555 |
`Synapses` object that declares the variable in its model equations. |
| 556 |
size : int or tuple of int |
| 557 |
The (initial) size of the variable. |
| 558 |
device : `Device` |
| 559 |
The device responsible for the memory access. |
| 560 |
dtype : `dtype`, optional |
| 561 |
The dtype used for storing the variable. If none is given, defaults |
| 562 |
to `core.default_float_dtype`. |
| 563 |
constant : bool, optional |
| 564 |
Whether the variable's value is constant during a run. |
| 565 |
Defaults to ``False``. |
| 566 |
needs_reference_update : bool, optional |
| 567 |
Whether the code objects need a new reference to the underlying data at |
| 568 |
every time step. This should be set if the size of the array can be |
| 569 |
changed by other code objects. Defaults to ``False``. |
| 570 |
scalar : bool, optional |
| 571 |
Whether this array is a 1-element array that should be treated like a |
| 572 |
scalar (e.g. for a single delay value across synapses). Defaults to |
| 573 |
``False``. |
| 574 |
read_only : bool, optional |
| 575 |
Whether this is a read-only variable, i.e. a variable that is set |
| 576 |
internally and cannot be changed by the user. Defaults |
| 577 |
to ``False``. |
| 578 |
unique : bool, optional |
| 579 |
Whether the values in this array are all unique. This information is |
| 580 |
only important for variables used as indices and does not have to |
| 581 |
reflect the actual contents of the array but only the possibility of |
| 582 |
non-uniqueness (e.g. synaptic indices are always unique but the |
| 583 |
corresponding pre- and post-synaptic indices are not). Defaults to |
| 584 |
``False``. |
| 585 |
""" |
| 586 |
|
| 587 |
# The size of a dynamic variable can of course change and changes in |
| 588 |
# size should not invalidate the cache |
| 589 |
_cache_irrelevant_attributes = ArrayVariable._cache_irrelevant_attributes | {"size"} |
| 590 |
|
| 591 |
def __init__( |
| 592 |
self, |
| 593 |
name, |
| 594 |
owner, |
| 595 |
size, |
| 596 |
device, |
| 597 |
dimensions=DIMENSIONLESS, |
| 598 |
dtype=None, |
| 599 |
constant=False, |
| 600 |
needs_reference_update=False, |
| 601 |
resize_along_first=False, |
| 602 |
scalar=False, |
| 603 |
read_only=False, |
| 604 |
unique=False, |
| 605 |
): |
| 606 |
if isinstance(size, int): |
| 607 |
ndim = 1 |
| 608 |
else: |
| 609 |
ndim = len(size) |
| 610 |
|
| 611 |
#: The number of dimensions |
| 612 |
self.ndim = ndim |
| 613 |
|
| 614 |
if constant and needs_reference_update: |
| 615 |
raise ValueError("A variable cannot be constant and need reference updates") |
| 616 |
#: Whether this variable needs an update of the reference to the |
| 617 |
#: underlying data whenever it is passed to a code object |
| 618 |
self.needs_reference_update = needs_reference_update |
| 619 |
|
| 620 |
#: Whether this array will be only resized along the first dimension |
| 621 |
self.resize_along_first = resize_along_first |
| 622 |
|
| 623 |
super().__init__( |
| 624 |
dimensions=dimensions, |
| 625 |
owner=owner, |
| 626 |
name=name, |
| 627 |
size=size, |
| 628 |
device=device, |
| 629 |
constant=constant, |
| 630 |
dtype=dtype, |
| 631 |
scalar=scalar, |
| 632 |
dynamic=True, |
| 633 |
read_only=read_only, |
| 634 |
unique=unique, |
| 635 |
) |
| 636 |
|
| 637 |
@property |
| 638 |
def dimensions(self): |
| 639 |
logger.warn( |
| 640 |
"The DynamicArrayVariable.dimensions attribute is " |
| 641 |
"deprecated, use .ndim instead", |
| 642 |
"deprecated_dimensions", |
| 643 |
once=True, |
| 644 |
) |
| 645 |
return self.ndim |
| 646 |
|
| 647 |
def resize(self, new_size): |
| 648 |
""" |
| 649 |
Resize the dynamic array. Calls `self.device.resize` to do the |
| 650 |
actual resizing. |
| 651 |
|
| 652 |
Parameters |
| 653 |
---------- |
| 654 |
new_size : int or tuple of int |
| 655 |
The new size. |
| 656 |
""" |
| 657 |
if self.resize_along_first: |
| 658 |
self.device.resize_along_first(self, new_size) |
| 659 |
else: |
| 660 |
self.device.resize(self, new_size) |
| 661 |
|
| 662 |
self.size = new_size |
| 663 |
|
| 664 |
def get_capsule(self): |
| 665 |
""" |
| 666 |
Get a PyCapsule object for direct C++ pointer access. |
| 667 |
|
| 668 |
This provides safe access to the underlying C++ dynamic array object |
| 669 |
for high-performance operations in Cython code. |
| 670 |
|
| 671 |
Returns |
| 672 |
------- |
| 673 |
capsule : PyCapsule |
| 674 |
A PyCapsule containing the C++ pointer to the dynamic array. |
| 675 |
|
| 676 |
""" |
| 677 |
return self.device.get_capsule(self) |
| 678 |
|
| 679 |
|
| 680 |
class Subexpression(Variable): |
| 681 |
""" |
| 682 |
An object providing information about a named subexpression in a model. |
| 683 |
Most of the time `Variables.add_subexpression` should be used instead of |
| 684 |
instantiating this class directly. |
| 685 |
|
| 686 |
Parameters |
| 687 |
---------- |
| 688 |
name : str |
| 689 |
The name of the subexpression. |
| 690 |
dimensions : `Dimension`, optional |
| 691 |
The physical dimensions of the subexpression. |
| 692 |
owner : `Group` |
| 693 |
The group to which the expression refers. |
| 694 |
expr : str |
| 695 |
The subexpression itself. |
| 696 |
device : `Device` |
| 697 |
The device responsible for the memory access. |
| 698 |
dtype : `dtype`, optional |
| 699 |
The dtype used for the expression. Defaults to |
| 700 |
`core.default_float_dtype`. |
| 701 |
scalar: bool, optional |
| 702 |
Whether this is an expression only referring to scalar variables. |
| 703 |
Defaults to ``False`` |
| 704 |
""" |
| 705 |
|
| 706 |
def __init__( |
| 707 |
self, |
| 708 |
name, |
| 709 |
owner, |
| 710 |
expr, |
| 711 |
device, |
| 712 |
dimensions=DIMENSIONLESS, |
| 713 |
dtype=None, |
| 714 |
scalar=False, |
| 715 |
): |
| 716 |
super().__init__( |
| 717 |
dimensions=dimensions, |
| 718 |
owner=owner, |
| 719 |
name=name, |
| 720 |
dtype=dtype, |
| 721 |
scalar=scalar, |
| 722 |
constant=False, |
| 723 |
read_only=True, |
| 724 |
) |
| 725 |
|
| 726 |
#: The `Device` responsible for memory access |
| 727 |
self.device = device |
| 728 |
|
| 729 |
#: The expression defining the subexpression |
| 730 |
self.expr = expr.strip() |
| 731 |
|
| 732 |
#: The identifiers used in the expression |
| 733 |
self.identifiers = get_identifiers(expr) |
| 734 |
|
| 735 |
def get_addressable_value(self, name, group): |
| 736 |
return VariableView( |
| 737 |
name=name, variable=self, group=group, dimensions=DIMENSIONLESS |
| 738 |
) |
| 739 |
|
| 740 |
def get_addressable_value_with_unit(self, name, group): |
| 741 |
return VariableView(name=name, variable=self, group=group, dimensions=self.dim) |
| 742 |
|
| 743 |
def __contains__(self, var): |
| 744 |
return var in self.identifiers |
| 745 |
|
| 746 |
def __repr__(self): |
| 747 |
description = ( |
| 748 |
"<{classname}(name={name}, dimensions={dimensions}, dtype={dtype}, " |
| 749 |
"expr={expr}, owner=<{owner}>)>" |
| 750 |
) |
| 751 |
return description.format( |
| 752 |
classname=self.__class__.__name__, |
| 753 |
name=repr(self.name), |
| 754 |
dimensions=repr(self.dim), |
| 755 |
dtype=repr(self.dtype), |
| 756 |
expr=repr(self.expr), |
| 757 |
owner=self.owner.name, |
| 758 |
) |
| 759 |
|
| 760 |
|
| 761 |
# ------------------------------------------------------------------------------ |
| 762 |
# Classes providing views on variables and storing variables information |
| 763 |
# ------------------------------------------------------------------------------ |
| 764 |
class LinkedVariable: |
| 765 |
""" |
| 766 |
A simple helper class to make linking variables explicit. Users should use |
| 767 |
`linked_var` instead. |
| 768 |
|
| 769 |
Parameters |
| 770 |
---------- |
| 771 |
group : `Group` |
| 772 |
The group through which the `variable` is accessed (not necessarily the |
| 773 |
same as ``variable.owner``. |
| 774 |
name : str |
| 775 |
The name of `variable` in `group` (not necessarily the same as |
| 776 |
``variable.name``). |
| 777 |
variable : `Variable` |
| 778 |
The variable that should be linked. |
| 779 |
index : str or `ndarray`, optional |
| 780 |
An indexing array (or the name of a state variable), providing a mapping |
| 781 |
from the entries in the link source to the link target. |
| 782 |
""" |
| 783 |
|
| 784 |
def __init__(self, group, name, variable, index=None): |
| 785 |
if isinstance(variable, DynamicArrayVariable): |
| 786 |
raise NotImplementedError( |
| 787 |
f"Linking to variable {variable.name} is " |
| 788 |
"not supported, can only link to " |
| 789 |
"state variables of fixed size." |
| 790 |
) |
| 791 |
self.group = group |
| 792 |
self.name = name |
| 793 |
self.variable = variable |
| 794 |
self.index = index |
| 795 |
|
| 796 |
|
| 797 |
def linked_var(group_or_variable, name=None, index=None): |
| 798 |
""" |
| 799 |
Represents a link target for setting a linked variable. |
| 800 |
|
| 801 |
Parameters |
| 802 |
---------- |
| 803 |
group_or_variable : `NeuronGroup` or `VariableView` |
| 804 |
Either a reference to the target `NeuronGroup` (e.g. ``G``) or a direct |
| 805 |
reference to a `VariableView` object (e.g. ``G.v``). In case only the |
| 806 |
group is specified, `name` has to be specified as well. |
| 807 |
name : str, optional |
| 808 |
The name of the target variable, necessary if `group_or_variable` is a |
| 809 |
`NeuronGroup`. |
| 810 |
index : str or `ndarray`, optional |
| 811 |
An indexing array (or the name of a state variable), providing a mapping |
| 812 |
from the entries in the link source to the link target. |
| 813 |
|
| 814 |
Examples |
| 815 |
-------- |
| 816 |
>>> from brian2 import * |
| 817 |
>>> G1 = NeuronGroup(10, 'dv/dt = -v / (10*ms) : volt') |
| 818 |
>>> G2 = NeuronGroup(10, 'v : volt (linked)') |
| 819 |
>>> G2.v = linked_var(G1, 'v') |
| 820 |
>>> G2.v = linked_var(G1.v) # equivalent |
| 821 |
""" |
| 822 |
if isinstance(group_or_variable, VariableView): |
| 823 |
if name is not None: |
| 824 |
raise ValueError( |
| 825 |
"Cannot give a variable and a variable name at the same time." |
| 826 |
) |
| 827 |
return LinkedVariable( |
| 828 |
group_or_variable.group, |
| 829 |
group_or_variable.name, |
| 830 |
group_or_variable.variable, |
| 831 |
index=index, |
| 832 |
) |
| 833 |
elif name is None: |
| 834 |
raise ValueError("Need to provide a variable name") |
| 835 |
else: |
| 836 |
return LinkedVariable( |
| 837 |
group_or_variable, name, group_or_variable.variables[name], index=index |
| 838 |
) |
| 839 |
|
| 840 |
|
| 841 |
class VariableView: |
| 842 |
""" |
| 843 |
A view on a variable that allows to treat it as an numpy array while |
| 844 |
allowing special indexing (e.g. with strings) in the context of a `Group`. |
| 845 |
|
| 846 |
Parameters |
| 847 |
---------- |
| 848 |
name : str |
| 849 |
The name of the variable (not necessarily the same as ``variable.name``). |
| 850 |
variable : `Variable` |
| 851 |
The variable description. |
| 852 |
group : `Group` |
| 853 |
The group through which the variable is accessed (not necessarily the |
| 854 |
same as `variable.owner`). |
| 855 |
dimensions : `Dimension`, optional |
| 856 |
The physical dimensions to be used for the variable, should be `None` |
| 857 |
when a variable is accessed without units (e.g. when accessing |
| 858 |
``G.var_``). |
| 859 |
""" |
| 860 |
|
| 861 |
__array_priority__ = 10 |
| 862 |
|
| 863 |
def __init__(self, name, variable, group, dimensions=None): |
| 864 |
self.name = name |
| 865 |
self.variable = variable |
| 866 |
self.index_var_name = group.variables.indices[name] |
| 867 |
if self.index_var_name in ("_idx", "0"): |
| 868 |
self.index_var = self.index_var_name |
| 869 |
else: |
| 870 |
self.index_var = group.variables[self.index_var_name] |
| 871 |
|
| 872 |
if isinstance(variable, Subexpression): |
| 873 |
# For subexpressions, we *always* have to go via codegen to get |
| 874 |
# their value -- since we cannot do this without the group, we |
| 875 |
# hold a strong reference |
| 876 |
self.group = group |
| 877 |
else: |
| 878 |
# For state variable arrays, we can do most access without the full |
| 879 |
# group, using the indexing reference below. We therefore only keep |
| 880 |
# a weak reference to the group. |
| 881 |
self.group = weakproxy_with_fallback(group) |
| 882 |
self.group_name = group.name |
| 883 |
# We keep a strong reference to the `Indexing` object so that basic |
| 884 |
# indexing is still possible, even if the group no longer exists |
| 885 |
self.indexing = self.group._indices |
| 886 |
self.dim = dimensions |
| 887 |
|
| 888 |
@property |
| 889 |
def unit(self): |
| 890 |
""" |
| 891 |
The `Unit` of this variable |
| 892 |
""" |
| 893 |
return get_unit(self.dim) |
| 894 |
|
| 895 |
def get_item(self, item, level=0, namespace=None): |
| 896 |
""" |
| 897 |
Get the value of this variable. Called by `__getitem__`. |
| 898 |
|
| 899 |
Parameters |
| 900 |
---------- |
| 901 |
item : slice, `ndarray` or string |
| 902 |
The index for the setting operation |
| 903 |
level : int, optional |
| 904 |
How much farther to go up in the stack to find the implicit |
| 905 |
namespace (if used, see `run_namespace`). |
| 906 |
namespace : dict-like, optional |
| 907 |
An additional namespace that is used for variable lookup (if not |
| 908 |
defined, the implicit namespace of local variables is used). |
| 909 |
""" |
| 910 |
from brian2.core.namespace import get_local_namespace # avoids circular import |
| 911 |
|
| 912 |
if isinstance(item, str): |
| 913 |
# Check whether the group still exists to give a more meaningful |
| 914 |
# error message if it does not |
| 915 |
try: |
| 916 |
self.group.name |
| 917 |
except ReferenceError: |
| 918 |
raise ReferenceError( |
| 919 |
"Cannot use string expressions, the " |
| 920 |
f"group '{self.group_name}', providing the " |
| 921 |
"context for the expression, no longer exists. " |
| 922 |
"Consider holding an explicit reference " |
| 923 |
"to it to keep it alive." |
| 924 |
) from None |
| 925 |
if namespace is None: |
| 926 |
namespace = get_local_namespace(level=level + 1) |
| 927 |
values = self.get_with_expression(item, run_namespace=namespace) |
| 928 |
else: |
| 929 |
if isinstance(self.variable, Subexpression): |
| 930 |
if namespace is None: |
| 931 |
namespace = get_local_namespace(level=level + 1) |
| 932 |
values = self.get_subexpression_with_index_array( |
| 933 |
item, run_namespace=namespace |
| 934 |
) |
| 935 |
else: |
| 936 |
values = self.get_with_index_array(item) |
| 937 |
|
| 938 |
if self.dim is DIMENSIONLESS or self.dim is None: |
| 939 |
return values |
| 940 |
else: |
| 941 |
return Quantity(values, self.dim) |
| 942 |
|
| 943 |
def __getitem__(self, item): |
| 944 |
return self.get_item(item, level=1) |
| 945 |
|
| 946 |
def set_item(self, item, value, level=0, namespace=None): |
| 947 |
""" |
| 948 |
Set this variable. This function is called by `__setitem__` but there |
| 949 |
is also a situation where it should be called directly: if the context |
| 950 |
for string-based expressions is higher up in the stack, this function |
| 951 |
allows to set the `level` argument accordingly. |
| 952 |
|
| 953 |
Parameters |
| 954 |
---------- |
| 955 |
item : slice, `ndarray` or string |
| 956 |
The index for the setting operation |
| 957 |
value : `Quantity`, `ndarray` or number |
| 958 |
The value for the setting operation |
| 959 |
level : int, optional |
| 960 |
How much farther to go up in the stack to find the implicit |
| 961 |
namespace (if used, see `run_namespace`). |
| 962 |
namespace : dict-like, optional |
| 963 |
An additional namespace that is used for variable lookup (if not |
| 964 |
defined, the implicit namespace of local variables is used). |
| 965 |
""" |
| 966 |
from brian2.core.namespace import get_local_namespace # avoids circular import |
| 967 |
|
| 968 |
variable = self.variable |
| 969 |
if variable.read_only: |
| 970 |
raise TypeError(f"Variable {self.name} is read-only.") |
| 971 |
|
| 972 |
# Check whether the group allows writing to the variable (e.g. for |
| 973 |
# synaptic variables, writing is only allowed after a connect) |
| 974 |
try: |
| 975 |
self.group.check_variable_write(variable) |
| 976 |
except ReferenceError: |
| 977 |
# Ignore problems with weakly referenced groups that don't exist |
| 978 |
# anymore at this time (e.g. when doing neuron.axon.var = ...) |
| 979 |
pass |
| 980 |
|
| 981 |
# The second part is equivalent to item == slice(None) but formulating |
| 982 |
# it this way prevents a FutureWarning if one of the elements is a |
| 983 |
# numpy array |
| 984 |
if isinstance(item, slice) and ( |
| 985 |
item.start is None and item.stop is None and item.step is None |
| 986 |
): |
| 987 |
item = "True" |
| 988 |
|
| 989 |
check_units = self.dim is not None |
| 990 |
|
| 991 |
if namespace is None: |
| 992 |
namespace = get_local_namespace(level=level + 1) |
| 993 |
|
| 994 |
# Both index and values are strings, use a single code object do deal |
| 995 |
# with this situation |
| 996 |
if isinstance(value, str) and isinstance(item, str): |
| 997 |
self.set_with_expression_conditional( |
| 998 |
item, value, check_units=check_units, run_namespace=namespace |
| 999 |
) |
| 1000 |
elif isinstance(item, str): |
| 1001 |
try: |
| 1002 |
if isinstance(value, str): |
| 1003 |
raise TypeError # Will be dealt with below |
| 1004 |
value = np.asanyarray(value).item() |
| 1005 |
except (TypeError, ValueError): |
| 1006 |
if item != "True": |
| 1007 |
raise TypeError( |
| 1008 |
"When setting a variable based on a string " |
| 1009 |
"index, the value has to be a string or a " |
| 1010 |
"scalar." |
| 1011 |
) from None |
| 1012 |
|
| 1013 |
if item == "True": |
| 1014 |
# We do not want to go through code generation for runtime |
| 1015 |
self.set_with_index_array(slice(None), value, check_units=check_units) |
| 1016 |
else: |
| 1017 |
self.set_with_expression_conditional( |
| 1018 |
item, repr(value), check_units=check_units, run_namespace=namespace |
| 1019 |
) |
| 1020 |
elif isinstance(value, str): |
| 1021 |
self.set_with_expression( |
| 1022 |
item, value, check_units=check_units, run_namespace=namespace |
| 1023 |
) |
| 1024 |
else: # No string expressions involved |
| 1025 |
self.set_with_index_array(item, value, check_units=check_units) |
| 1026 |
|
| 1027 |
def __setitem__(self, item, value): |
| 1028 |
self.set_item(item, value, level=1) |
| 1029 |
|
| 1030 |
@device_override("variableview_set_with_expression") |
| 1031 |
def set_with_expression(self, item, code, run_namespace, check_units=True): |
| 1032 |
""" |
| 1033 |
Sets a variable using a string expression. Is called by |
| 1034 |
`VariableView.set_item` for statements such as |
| 1035 |
``S.var[:, :] = 'exp(-abs(i-j)/space_constant)*nS'`` |
| 1036 |
|
| 1037 |
Parameters |
| 1038 |
---------- |
| 1039 |
item : `ndarray` |
| 1040 |
The indices for the variable (in the context of this `group`). |
| 1041 |
code : str |
| 1042 |
The code that should be executed to set the variable values. |
| 1043 |
Can contain references to indices, such as `i` or `j` |
| 1044 |
run_namespace : dict-like, optional |
| 1045 |
An additional namespace that is used for variable lookup (if not |
| 1046 |
defined, the implicit namespace of local variables is used). |
| 1047 |
check_units : bool, optional |
| 1048 |
Whether to check the units of the expression. |
| 1049 |
run_namespace : dict-like, optional |
| 1050 |
An additional namespace that is used for variable lookup (if not |
| 1051 |
defined, the implicit namespace of local variables is used). |
| 1052 |
""" |
| 1053 |
# Some fairly complicated code to raise a warning in ambiguous |
| 1054 |
# situations, when indexing with a group. For example, in: |
| 1055 |
# group.v[subgroup] = 'i' |
| 1056 |
# the index 'i' is the index of 'group' ("absolute index") and not of |
| 1057 |
# subgroup ("relative index") |
| 1058 |
if hasattr(item, "variables") or ( |
| 1059 |
isinstance(item, tuple) |
| 1060 |
and any(hasattr(one_item, "variables") for one_item in item) |
| 1061 |
): |
| 1062 |
# Determine the variables that are used in the expression |
| 1063 |
from brian2.codegen.translation import get_identifiers_recursively |
| 1064 |
|
| 1065 |
identifiers = get_identifiers_recursively([code], self.group.variables) |
| 1066 |
variables = self.group.resolve_all( |
| 1067 |
identifiers, run_namespace, user_identifiers=set() |
| 1068 |
) |
| 1069 |
if not isinstance(item, tuple): |
| 1070 |
index_groups = [item] |
| 1071 |
else: |
| 1072 |
index_groups = item |
| 1073 |
|
| 1074 |
for varname, var in variables.items(): |
| 1075 |
for index_group in index_groups: |
| 1076 |
if not hasattr(index_group, "variables"): |
| 1077 |
continue |
| 1078 |
if ( |
| 1079 |
varname in index_group.variables |
| 1080 |
or var.name in index_group.variables |
| 1081 |
): |
| 1082 |
indexed_var = index_group.variables.get( |
| 1083 |
varname, index_group.variables.get(var.name) |
| 1084 |
) |
| 1085 |
if indexed_var is not var: |
| 1086 |
logger.warn( |
| 1087 |
"The string expression used for setting " |
| 1088 |
f"'{self.name}' refers to '{varname}' which " |
| 1089 |
"might be ambiguous. It will be " |
| 1090 |
"interpreted as referring to " |
| 1091 |
f"'{varname}' in '{self.group.name}', not as " |
| 1092 |
"a variable of a group used for " |
| 1093 |
"indexing.", |
| 1094 |
"ambiguous_string_expression", |
| 1095 |
) |
| 1096 |
break # no need to warn more than once for a variable |
| 1097 |
|
| 1098 |
indices = np.atleast_1d(self.indexing(item)) |
| 1099 |
abstract_code = f"{self.name} = {code}" |
| 1100 |
variables = Variables(self.group) |
| 1101 |
variables.add_array( |
| 1102 |
"_group_idx", size=len(indices), dtype=np.int32, values=indices |
| 1103 |
) |
| 1104 |
|
| 1105 |
# TODO: Have an additional argument to avoid going through the index |
| 1106 |
# array for situations where iterate_all could be used |
| 1107 |
from brian2.codegen.codeobject import create_runner_codeobj |
| 1108 |
from brian2.devices.device import get_device |
| 1109 |
|
| 1110 |
device = get_device() |
| 1111 |
|
| 1112 |
codeobj = create_runner_codeobj( |
| 1113 |
self.group, |
| 1114 |
abstract_code, |
| 1115 |
"group_variable_set", |
| 1116 |
additional_variables=variables, |
| 1117 |
check_units=check_units, |
| 1118 |
run_namespace=run_namespace, |
| 1119 |
codeobj_class=device.code_object_class( |
| 1120 |
fallback_pref="codegen.string_expression_target" |
| 1121 |
), |
| 1122 |
) |
| 1123 |
codeobj() |
| 1124 |
|
| 1125 |
@device_override("variableview_set_with_expression_conditional") |
| 1126 |
def set_with_expression_conditional( |
| 1127 |
self, cond, code, run_namespace, check_units=True |
| 1128 |
): |
| 1129 |
""" |
| 1130 |
Sets a variable using a string expression and string condition. Is |
| 1131 |
called by `VariableView.set_item` for statements such as |
| 1132 |
``S.var['i!=j'] = 'exp(-abs(i-j)/space_constant)*nS'`` |
| 1133 |
|
| 1134 |
Parameters |
| 1135 |
---------- |
| 1136 |
cond : str |
| 1137 |
The string condition for which the variables should be set. |
| 1138 |
code : str |
| 1139 |
The code that should be executed to set the variable values. |
| 1140 |
run_namespace : dict-like, optional |
| 1141 |
An additional namespace that is used for variable lookup (if not |
| 1142 |
defined, the implicit namespace of local variables is used). |
| 1143 |
check_units : bool, optional |
| 1144 |
Whether to check the units of the expression. |
| 1145 |
""" |
| 1146 |
variable = self.variable |
| 1147 |
if variable.scalar and cond != "True": |
| 1148 |
raise IndexError( |
| 1149 |
f"Cannot conditionally set the scalar variable '{self.name}'." |
| 1150 |
) |
| 1151 |
abstract_code_cond = f"_cond = {cond}" |
| 1152 |
abstract_code = f"{self.name} = {code}" |
| 1153 |
variables = Variables(None) |
| 1154 |
variables.add_auxiliary_variable("_cond", dtype=bool) |
| 1155 |
from brian2.codegen.codeobject import create_runner_codeobj |
| 1156 |
|
| 1157 |
# TODO: Have an additional argument to avoid going through the index |
| 1158 |
# array for situations where iterate_all could be used |
| 1159 |
from brian2.devices.device import get_device |
| 1160 |
|
| 1161 |
device = get_device() |
| 1162 |
codeobj = create_runner_codeobj( |
| 1163 |
self.group, |
| 1164 |
{"condition": abstract_code_cond, "statement": abstract_code}, |
| 1165 |
"group_variable_set_conditional", |
| 1166 |
additional_variables=variables, |
| 1167 |
check_units=check_units, |
| 1168 |
run_namespace=run_namespace, |
| 1169 |
codeobj_class=device.code_object_class( |
| 1170 |
fallback_pref="codegen.string_expression_target" |
| 1171 |
), |
| 1172 |
) |
| 1173 |
codeobj() |
| 1174 |
|
| 1175 |
@device_override("variableview_get_with_expression") |
| 1176 |
def get_with_expression(self, code, run_namespace): |
| 1177 |
""" |
| 1178 |
Gets a variable using a string expression. Is called by |
| 1179 |
`VariableView.get_item` for statements such as |
| 1180 |
``print(G.v['g_syn > 0'])``. |
| 1181 |
|
| 1182 |
Parameters |
| 1183 |
---------- |
| 1184 |
code : str |
| 1185 |
An expression that states a condition for elements that should be |
| 1186 |
selected. Can contain references to indices, such as ``i`` or ``j`` |
| 1187 |
and to state variables. For example: ``'i>3 and v>0*mV'``. |
| 1188 |
run_namespace : dict-like |
| 1189 |
An additional namespace that is used for variable lookup (either |
| 1190 |
an explicitly defined namespace or one taken from the local |
| 1191 |
context). |
| 1192 |
""" |
| 1193 |
variable = self.variable |
| 1194 |
if variable.scalar: |
| 1195 |
raise IndexError( |
| 1196 |
f"Cannot access the variable '{self.name}' with a " |
| 1197 |
"string expression, it is a scalar variable." |
| 1198 |
) |
| 1199 |
# Add the recorded variable under a known name to the variables |
| 1200 |
# dictionary. Important to deal correctly with |
| 1201 |
# the type of the variable in C++ |
| 1202 |
variables = Variables(None) |
| 1203 |
variables.add_auxiliary_variable( |
| 1204 |
"_variable", |
| 1205 |
dimensions=variable.dim, |
| 1206 |
dtype=variable.dtype, |
| 1207 |
scalar=variable.scalar, |
| 1208 |
) |
| 1209 |
variables.add_auxiliary_variable("_cond", dtype=bool) |
| 1210 |
|
| 1211 |
abstract_code = f"_variable = {self.name}\n" |
| 1212 |
abstract_code += f"_cond = {code}" |
| 1213 |
from brian2.codegen.codeobject import create_runner_codeobj |
| 1214 |
from brian2.devices.device import get_device |
| 1215 |
|
| 1216 |
device = get_device() |
| 1217 |
codeobj = create_runner_codeobj( |
| 1218 |
self.group, |
| 1219 |
abstract_code, |
| 1220 |
"group_variable_get_conditional", |
| 1221 |
additional_variables=variables, |
| 1222 |
run_namespace=run_namespace, |
| 1223 |
codeobj_class=device.code_object_class( |
| 1224 |
fallback_pref="codegen.string_expression_target" |
| 1225 |
), |
| 1226 |
) |
| 1227 |
return codeobj() |
| 1228 |
|
| 1229 |
@device_override("variableview_get_with_index_array") |
| 1230 |
def get_with_index_array(self, item): |
| 1231 |
variable = self.variable |
| 1232 |
if variable.scalar: |
| 1233 |
if not (isinstance(item, slice) and item == slice(None)): |
| 1234 |
raise IndexError( |
| 1235 |
f"Illegal index for variable '{self.name}', it is a " |
| 1236 |
"scalar variable." |
| 1237 |
) |
| 1238 |
indices = 0 |
| 1239 |
elif ( |
| 1240 |
isinstance(item, slice) and item == slice(None) and self.index_var == "_idx" |
| 1241 |
): |
| 1242 |
indices = slice(None) |
| 1243 |
# Quick fix for matplotlib calling 1-d variables as var[:, np.newaxis] |
| 1244 |
# The test is a bit verbose, but we need to avoid comparisons that raise errors |
| 1245 |
# (e.g. comparing an array to slice(None)) |
| 1246 |
elif ( |
| 1247 |
isinstance(item, tuple) |
| 1248 |
and len(item) == 2 |
| 1249 |
and isinstance(item[0], slice) |
| 1250 |
and item[0] == slice(None) |
| 1251 |
and item[1] is None |
| 1252 |
): |
| 1253 |
if self.index_var == "_idx": |
| 1254 |
return variable.get_value()[item] |
| 1255 |
else: |
| 1256 |
return variable.get_value()[self.index_var.get_value()][item] |
| 1257 |
else: |
| 1258 |
indices = self.indexing(item, self.index_var) |
| 1259 |
|
| 1260 |
return variable.get_value()[indices] |
| 1261 |
|
| 1262 |
@device_override("variableview_get_subexpression_with_index_array") |
| 1263 |
def get_subexpression_with_index_array(self, item, run_namespace): |
| 1264 |
variable = self.variable |
| 1265 |
if variable.scalar: |
| 1266 |
if not (isinstance(item, slice) and item == slice(None)): |
| 1267 |
raise IndexError( |
| 1268 |
f"Illegal index for variable '{self.name}', it is a " |
| 1269 |
"scalar variable." |
| 1270 |
) |
| 1271 |
indices = np.array(0) |
| 1272 |
else: |
| 1273 |
indices = self.indexing(item, self.index_var) |
| 1274 |
|
| 1275 |
# For "normal" variables, we can directly access the underlying data |
| 1276 |
# and use the usual slicing syntax. For subexpressions, however, we |
| 1277 |
# have to evaluate code for the given indices |
| 1278 |
variables = Variables(None, default_index="_group_index") |
| 1279 |
variables.add_auxiliary_variable( |
| 1280 |
"_variable", |
| 1281 |
dimensions=variable.dim, |
| 1282 |
dtype=variable.dtype, |
| 1283 |
scalar=variable.scalar, |
| 1284 |
) |
| 1285 |
if indices.shape == (): |
| 1286 |
single_index = True |
| 1287 |
indices = np.array([indices]) |
| 1288 |
else: |
| 1289 |
single_index = False |
| 1290 |
variables.add_array("_group_idx", size=len(indices), dtype=np.int32) |
| 1291 |
variables["_group_idx"].set_value(indices) |
| 1292 |
# Force the use of this variable as a replacement for the original |
| 1293 |
# index variable |
| 1294 |
using_orig_index = [ |
| 1295 |
varname |
| 1296 |
for varname, index in self.group.variables.indices.items() |
| 1297 |
if index == self.index_var_name and index != "0" |
| 1298 |
] |
| 1299 |
for varname in using_orig_index: |
| 1300 |
variables.indices[varname] = "_idx" |
| 1301 |
|
| 1302 |
abstract_code = f"_variable = {self.name}\n" |
| 1303 |
from brian2.codegen.codeobject import create_runner_codeobj |
| 1304 |
from brian2.devices.device import get_device |
| 1305 |
|
| 1306 |
device = get_device() |
| 1307 |
codeobj = create_runner_codeobj( |
| 1308 |
self.group, |
| 1309 |
abstract_code, |
| 1310 |
"group_variable_get", |
| 1311 |
# Setting the user code to an empty |
| 1312 |
# string suppresses warnings if the |
| 1313 |
# subexpression refers to variable |
| 1314 |
# names that are also present in the |
| 1315 |
# local namespace |
| 1316 |
user_code="", |
| 1317 |
needed_variables=["_group_idx"], |
| 1318 |
additional_variables=variables, |
| 1319 |
run_namespace=run_namespace, |
| 1320 |
codeobj_class=device.code_object_class( |
| 1321 |
fallback_pref="codegen.string_expression_target" |
| 1322 |
), |
| 1323 |
) |
| 1324 |
result = codeobj() |
| 1325 |
if single_index and not variable.scalar: |
| 1326 |
return result[0] |
| 1327 |
else: |
| 1328 |
return result |
| 1329 |
|
| 1330 |
@device_override("variableview_set_with_index_array") |
| 1331 |
def set_with_index_array(self, item, value, check_units): |
| 1332 |
variable = self.variable |
| 1333 |
if check_units: |
| 1334 |
fail_for_dimension_mismatch( |
| 1335 |
variable.dim, value, f"Incorrect unit for setting variable {self.name}" |
| 1336 |
) |
| 1337 |
if variable.scalar: |
| 1338 |
if not (isinstance(item, slice) and item == slice(None)): |
| 1339 |
raise IndexError( |
| 1340 |
"Illegal index for variable '{self.name}', it is a scalar variable." |
| 1341 |
) |
| 1342 |
indices = 0 |
| 1343 |
elif ( |
| 1344 |
isinstance(item, slice) and item == slice(None) and self.index_var == "_idx" |
| 1345 |
): |
| 1346 |
indices = slice(None) |
| 1347 |
else: |
| 1348 |
indices = self.indexing(item, self.index_var) |
| 1349 |
|
| 1350 |
q = Quantity(value) |
| 1351 |
if len(q.shape): |
| 1352 |
if not len(q.shape) == 1 or len(q) != 1 and len(q) != len(indices): |
| 1353 |
raise ValueError( |
| 1354 |
"Provided values do not match the size " |
| 1355 |
"of the indices, " |
| 1356 |
f"{len(q)} != {len(indices)}." |
| 1357 |
) |
| 1358 |
variable.get_value()[indices] = value |
| 1359 |
|
| 1360 |
# Allow some basic calculations directly on the ArrayView object |
| 1361 |
def __array__(self, dtype=None, copy=None): |
| 1362 |
try: |
| 1363 |
# This will fail for subexpressions that refer to external |
| 1364 |
# parameters |
| 1365 |
values = self[:] |
| 1366 |
# Never hand over copy = None |
| 1367 |
return np.array(values, dtype=dtype, copy=copy is not False, subok=True) |
| 1368 |
except ValueError: |
| 1369 |
var = self.variable.name |
| 1370 |
raise ValueError( |
| 1371 |
f"Cannot get the values for variable {var}. If it " |
| 1372 |
"is a subexpression referring to external " |
| 1373 |
f"variables, use 'group.{var}[:]' instead of " |
| 1374 |
f"'group.{var}'" |
| 1375 |
) from None |
| 1376 |
|
| 1377 |
def __array__ufunc__(self, ufunc, method, *inputs, **kwargs): |
| 1378 |
if method == "__call__": |
| 1379 |
return ufunc(self[:], *inputs, **kwargs) |
| 1380 |
else: |
| 1381 |
return NotImplemented |
| 1382 |
|
| 1383 |
def __len__(self): |
| 1384 |
return len(self.get_item(slice(None), level=1)) |
| 1385 |
|
| 1386 |
def __neg__(self): |
| 1387 |
return -self.get_item(slice(None), level=1) |
| 1388 |
|
| 1389 |
def __pos__(self): |
| 1390 |
return self.get_item(slice(None), level=1) |
| 1391 |
|
| 1392 |
def __add__(self, other): |
| 1393 |
return self.get_item(slice(None), level=1) + np.asanyarray(other) |
| 1394 |
|
| 1395 |
def __radd__(self, other): |
| 1396 |
return np.asanyarray(other) + self.get_item(slice(None), level=1) |
| 1397 |
|
| 1398 |
def __sub__(self, other): |
| 1399 |
return self.get_item(slice(None), level=1) - np.asanyarray(other) |
| 1400 |
|
| 1401 |
def __rsub__(self, other): |
| 1402 |
return np.asanyarray(other) - self.get_item(slice(None), level=1) |
| 1403 |
|
| 1404 |
def __mul__(self, other): |
| 1405 |
return self.get_item(slice(None), level=1) * np.asanyarray(other) |
| 1406 |
|
| 1407 |
def __rmul__(self, other): |
| 1408 |
return np.asanyarray(other) * self.get_item(slice(None), level=1) |
| 1409 |
|
| 1410 |
def __div__(self, other): |
| 1411 |
return self.get_item(slice(None), level=1) / np.asanyarray(other) |
| 1412 |
|
| 1413 |
def __truediv__(self, other): |
| 1414 |
return self.get_item(slice(None), level=1) / np.asanyarray(other) |
| 1415 |
|
| 1416 |
def __floordiv__(self, other): |
| 1417 |
return self.get_item(slice(None), level=1) // np.asanyarray(other) |
| 1418 |
|
| 1419 |
def __rdiv__(self, other): |
| 1420 |
return np.asanyarray(other) / self.get_item(slice(None), level=1) |
| 1421 |
|
| 1422 |
def __rtruediv__(self, other): |
| 1423 |
return np.asanyarray(other) / self.get_item(slice(None), level=1) |
| 1424 |
|
| 1425 |
def __rfloordiv__(self, other): |
| 1426 |
return np.asanyarray(other) // self.get_item(slice(None), level=1) |
| 1427 |
|
| 1428 |
def __mod__(self, other): |
| 1429 |
return self.get_item(slice(None), level=1) % np.asanyarray(other) |
| 1430 |
|
| 1431 |
def __pow__(self, power, modulo=None): |
| 1432 |
if modulo is not None: |
| 1433 |
return self.get_item(slice(None), level=1) ** power % modulo |
| 1434 |
else: |
| 1435 |
return self.get_item(slice(None), level=1) ** power |
| 1436 |
|
| 1437 |
def __rpow__(self, other): |
| 1438 |
if self.dim is not DIMENSIONLESS: |
| 1439 |
raise TypeError( |
| 1440 |
f"Cannot use '{self.name}' as an exponent, it has " |
| 1441 |
f"dimensions {get_unit_for_display(self.unit)}." |
| 1442 |
) |
| 1443 |
return other ** self.get_item(slice(None), level=1) |
| 1444 |
|
| 1445 |
def __iadd__(self, other): |
| 1446 |
if isinstance(other, str): |
| 1447 |
raise TypeError( |
| 1448 |
"In-place modification with strings not " |
| 1449 |
"supported. Use group.var = 'var + expression' " |
| 1450 |
"instead of group.var += 'expression'." |
| 1451 |
) |
| 1452 |
elif isinstance(self.variable, Subexpression): |
| 1453 |
raise TypeError("Cannot assign to a subexpression.") |
| 1454 |
else: |
| 1455 |
rhs = self[:] + np.asanyarray(other) |
| 1456 |
self[:] = rhs |
| 1457 |
return self |
| 1458 |
|
| 1459 |
# Support matrix multiplication with @ |
| 1460 |
def __matmul__(self, other): |
| 1461 |
return self.get_item(slice(None), level=1) @ np.asanyarray(other) |
| 1462 |
|
| 1463 |
def __rmatmul__(self, other): |
| 1464 |
return np.asanyarray(other) @ self.get_item(slice(None), level=1) |
| 1465 |
|
| 1466 |
def __isub__(self, other): |
| 1467 |
if isinstance(other, str): |
| 1468 |
raise TypeError( |
| 1469 |
"In-place modification with strings not " |
| 1470 |
"supported. Use group.var = 'var - expression' " |
| 1471 |
"instead of group.var -= 'expression'." |
| 1472 |
) |
| 1473 |
elif isinstance(self.variable, Subexpression): |
| 1474 |
raise TypeError("Cannot assign to a subexpression.") |
| 1475 |
else: |
| 1476 |
rhs = self[:] - np.asanyarray(other) |
| 1477 |
self[:] = rhs |
| 1478 |
return self |
| 1479 |
|
| 1480 |
def __imul__(self, other): |
| 1481 |
if isinstance(other, str): |
| 1482 |
raise TypeError( |
| 1483 |
"In-place modification with strings not " |
| 1484 |
"supported. Use group.var = 'var * expression' " |
| 1485 |
"instead of group.var *= 'expression'." |
| 1486 |
) |
| 1487 |
elif isinstance(self.variable, Subexpression): |
| 1488 |
raise TypeError("Cannot assign to a subexpression.") |
| 1489 |
else: |
| 1490 |
rhs = self[:] * np.asanyarray(other) |
| 1491 |
self[:] = rhs |
| 1492 |
return self |
| 1493 |
|
| 1494 |
def __idiv__(self, other): |
| 1495 |
if isinstance(other, str): |
| 1496 |
raise TypeError( |
| 1497 |
"In-place modification with strings not " |
| 1498 |
"supported. Use group.var = 'var / expression' " |
| 1499 |
"instead of group.var /= 'expression'." |
| 1500 |
) |
| 1501 |
elif isinstance(self.variable, Subexpression): |
| 1502 |
raise TypeError("Cannot assign to a subexpression.") |
| 1503 |
else: |
| 1504 |
rhs = self[:] / np.asanyarray(other) |
| 1505 |
self[:] = rhs |
| 1506 |
return self |
| 1507 |
|
| 1508 |
def __ifloordiv__(self, other): |
| 1509 |
if isinstance(other, str): |
| 1510 |
raise TypeError( |
| 1511 |
"In-place modification with strings not " |
| 1512 |
"supported. Use group.var = 'var // expression' " |
| 1513 |
"instead of group.var //= 'expression'." |
| 1514 |
) |
| 1515 |
elif isinstance(self.variable, Subexpression): |
| 1516 |
raise TypeError("Cannot assign to a subexpression.") |
| 1517 |
else: |
| 1518 |
rhs = self[:] // np.asanyarray(other) |
| 1519 |
self[:] = rhs |
| 1520 |
return self |
| 1521 |
|
| 1522 |
def __imod__(self, other): |
| 1523 |
if isinstance(other, str): |
| 1524 |
raise TypeError( |
| 1525 |
"In-place modification with strings not " |
| 1526 |
"supported. Use group.var = 'var // expression' " |
| 1527 |
"instead of group.var //= 'expression'." |
| 1528 |
) |
| 1529 |
elif isinstance(self.variable, Subexpression): |
| 1530 |
raise TypeError("Cannot assign to a subexpression.") |
| 1531 |
else: |
| 1532 |
rhs = self[:] % np.asanyarray(other) |
| 1533 |
self[:] = rhs |
| 1534 |
return self |
| 1535 |
|
| 1536 |
def __ipow__(self, other): |
| 1537 |
if isinstance(other, str): |
| 1538 |
raise TypeError( |
| 1539 |
"In-place modification with strings not " |
| 1540 |
"supported. Use group.var = 'var ** expression' " |
| 1541 |
"instead of group.var **= 'expression'." |
| 1542 |
) |
| 1543 |
elif isinstance(self.variable, Subexpression): |
| 1544 |
raise TypeError("Cannot assign to a subexpression.") |
| 1545 |
else: |
| 1546 |
rhs = self[:] ** np.asanyarray(other) |
| 1547 |
self[:] = rhs |
| 1548 |
return self |
| 1549 |
|
| 1550 |
# Also allow logical comparisons |
| 1551 |
|
| 1552 |
def __eq__(self, other): |
| 1553 |
return self.get_item(slice(None), level=1) == np.asanyarray(other) |
| 1554 |
|
| 1555 |
def __ne__(self, other): |
| 1556 |
return self.get_item(slice(None), level=1) != np.asanyarray(other) |
| 1557 |
|
| 1558 |
def __lt__(self, other): |
| 1559 |
return self.get_item(slice(None), level=1) < np.asanyarray(other) |
| 1560 |
|
| 1561 |
def __le__(self, other): |
| 1562 |
return self.get_item(slice(None), level=1) <= np.asanyarray(other) |
| 1563 |
|
| 1564 |
def __gt__(self, other): |
| 1565 |
return self.get_item(slice(None), level=1) > np.asanyarray(other) |
| 1566 |
|
| 1567 |
def __ge__(self, other): |
| 1568 |
return self.get_item(slice(None), level=1) >= np.asanyarray(other) |
| 1569 |
|
| 1570 |
def __repr__(self): |
| 1571 |
varname = self.name |
| 1572 |
if self.dim is None: |
| 1573 |
varname += "_" |
| 1574 |
|
| 1575 |
if self.variable.scalar: |
| 1576 |
dim = self.dim if self.dim is not None else DIMENSIONLESS |
| 1577 |
values = repr(Quantity(self.variable.get_value().item(), dim=dim)) |
| 1578 |
else: |
| 1579 |
try: |
| 1580 |
# This will fail for subexpressions that refer to external |
| 1581 |
# parameters |
| 1582 |
values = repr(self[:]) |
| 1583 |
except KeyError: |
| 1584 |
values = ( |
| 1585 |
"[Subexpression refers to external parameters. Use " |
| 1586 |
f"'group.{self.variable.name}[:]']" |
| 1587 |
) |
| 1588 |
|
| 1589 |
return f"<{self.group_name}.{varname}: {values}>" |
| 1590 |
|
| 1591 |
def __hash__(self): |
| 1592 |
return hash((self.group_name, self.name)) |
| 1593 |
|
| 1594 |
# Get access to some basic properties of the underlying array |
| 1595 |
@property |
| 1596 |
def shape(self): |
| 1597 |
if isinstance(self.variable, DynamicArrayVariable): |
| 1598 |
# For dynamic variables, we need to make sure that their size is up-to-date in standalone mode |
| 1599 |
# We can trigger the update by asking for the values, even though we don't need them here |
| 1600 |
self.variable.get_value() |
| 1601 |
if self.ndim == 1: |
| 1602 |
if ( |
| 1603 |
hasattr(self, "group") |
| 1604 |
and hasattr(self.group, "start") |
| 1605 |
and hasattr(self.group, "stop") |
| 1606 |
): |
| 1607 |
# This is safer than using the variable size, since it also works for subgroups |
| 1608 |
# see GitHub issue #1555 |
| 1609 |
size = self.group.stop - self.group.start |
| 1610 |
assert size <= self.variable.size |
| 1611 |
else: |
| 1612 |
size = self.variable.size |
| 1613 |
|
| 1614 |
return (size,) |
| 1615 |
else: |
| 1616 |
return self.variable.size |
| 1617 |
|
| 1618 |
@property |
| 1619 |
def ndim(self): |
| 1620 |
return getattr(self.variable, "ndim", 1) |
| 1621 |
|
| 1622 |
@property |
| 1623 |
def dtype(self): |
| 1624 |
return self.variable.dtype |
| 1625 |
|
| 1626 |
|
| 1627 |
class Variables(Mapping): |
| 1628 |
""" |
| 1629 |
A container class for storing `Variable` objects. Instances of this class |
| 1630 |
are used as the `Group.variables` attribute and can be accessed as |
| 1631 |
(read-only) dictionaries. |
| 1632 |
|
| 1633 |
Parameters |
| 1634 |
---------- |
| 1635 |
owner : `Nameable` |
| 1636 |
The object (typically a `Group`) "owning" the variables. |
| 1637 |
default_index : str, optional |
| 1638 |
The index to use for the variables (only relevant for `ArrayVariable` |
| 1639 |
and `DynamicArrayVariable`). Defaults to ``'_idx'``. |
| 1640 |
""" |
| 1641 |
|
| 1642 |
def __init__(self, owner, default_index="_idx"): |
| 1643 |
#: A reference to the `Group` owning these variables |
| 1644 |
self.owner = weakproxy_with_fallback(owner) |
| 1645 |
# The index that is used for arrays if no index is given explicitly |
| 1646 |
self.default_index = default_index |
| 1647 |
|
| 1648 |
# We do the import here to avoid a circular dependency. |
| 1649 |
from brian2.devices.device import get_device |
| 1650 |
|
| 1651 |
self.device = get_device() |
| 1652 |
|
| 1653 |
self._variables = {} |
| 1654 |
#: A dictionary given the index name for every array name |
| 1655 |
self.indices = collections.defaultdict(functools.partial(str, default_index)) |
| 1656 |
# Note that by using functools.partial (instead of e.g. a lambda |
| 1657 |
# function) above, this object remains pickable. |
| 1658 |
|
| 1659 |
def __getstate__(self): |
| 1660 |
state = self.__dict__.copy() |
| 1661 |
state["owner"] = state["owner"].__repr__.__self__ |
| 1662 |
return state |
| 1663 |
|
| 1664 |
def __setstate__(self, state): |
| 1665 |
state["owner"] = weakproxy_with_fallback(state["owner"]) |
| 1666 |
self.__dict__ = state |
| 1667 |
|
| 1668 |
def __getitem__(self, item): |
| 1669 |
return self._variables[item] |
| 1670 |
|
| 1671 |
def __len__(self): |
| 1672 |
return len(self._variables) |
| 1673 |
|
| 1674 |
def __iter__(self): |
| 1675 |
return iter(self._variables) |
| 1676 |
|
| 1677 |
def _add_variable(self, name, var, index=None): |
| 1678 |
if name in self._variables: |
| 1679 |
raise KeyError( |
| 1680 |
f"The name '{name}' is already present in the variables dictionary." |
| 1681 |
) |
| 1682 |
# TODO: do some check for the name, part of it has to be device-specific |
| 1683 |
self._variables[name] = var |
| 1684 |
|
| 1685 |
if isinstance(var, ArrayVariable): |
| 1686 |
# Tell the device to actually create the array (or note it down for |
| 1687 |
# later code generation in standalone). |
| 1688 |
self.device.add_array(var) |
| 1689 |
|
| 1690 |
if getattr(var, "scalar", False): |
| 1691 |
if index not in (None, "0"): |
| 1692 |
raise ValueError("Cannot set an index for a scalar variable") |
| 1693 |
self.indices[name] = "0" |
| 1694 |
|
| 1695 |
if index is not None: |
| 1696 |
self.indices[name] = index |
| 1697 |
|
| 1698 |
def add_array( |
| 1699 |
self, |
| 1700 |
name, |
| 1701 |
size, |
| 1702 |
dimensions=DIMENSIONLESS, |
| 1703 |
values=None, |
| 1704 |
dtype=None, |
| 1705 |
constant=False, |
| 1706 |
read_only=False, |
| 1707 |
scalar=False, |
| 1708 |
unique=False, |
| 1709 |
index=None, |
| 1710 |
): |
| 1711 |
""" |
| 1712 |
Add an array (initialized with zeros). |
| 1713 |
|
| 1714 |
Parameters |
| 1715 |
---------- |
| 1716 |
name : str |
| 1717 |
The name of the variable. |
| 1718 |
dimensions : `Dimension`, optional |
| 1719 |
The physical dimensions of the variable. |
| 1720 |
size : int |
| 1721 |
The size of the array. |
| 1722 |
values : `ndarray`, optional |
| 1723 |
The values to initalize the array with. If not specified, the array |
| 1724 |
is initialized to zero. |
| 1725 |
dtype : `dtype`, optional |
| 1726 |
The dtype used for storing the variable. If none is given, defaults |
| 1727 |
to `core.default_float_dtype`. |
| 1728 |
constant : bool, optional |
| 1729 |
Whether the variable's value is constant during a run. |
| 1730 |
Defaults to ``False``. |
| 1731 |
scalar : bool, optional |
| 1732 |
Whether this is a scalar variable. Defaults to ``False``, if set to |
| 1733 |
``True``, also implies that `size` equals 1. |
| 1734 |
read_only : bool, optional |
| 1735 |
Whether this is a read-only variable, i.e. a variable that is set |
| 1736 |
internally and cannot be changed by the user. Defaults |
| 1737 |
to ``False``. |
| 1738 |
index : str, optional |
| 1739 |
The index to use for this variable. Defaults to |
| 1740 |
`Variables.default_index`. |
| 1741 |
unique : bool, optional |
| 1742 |
See `ArrayVariable`. Defaults to ``False``. |
| 1743 |
""" |
| 1744 |
if np.asanyarray(size).shape == (): |
| 1745 |
# We want a basic Python type for the size instead of something |
| 1746 |
# like numpy.int64 |
| 1747 |
size = int(size) |
| 1748 |
var = ArrayVariable( |
| 1749 |
name=name, |
| 1750 |
dimensions=dimensions, |
| 1751 |
owner=self.owner, |
| 1752 |
device=self.device, |
| 1753 |
size=size, |
| 1754 |
dtype=dtype, |
| 1755 |
constant=constant, |
| 1756 |
scalar=scalar, |
| 1757 |
read_only=read_only, |
| 1758 |
unique=unique, |
| 1759 |
) |
| 1760 |
self._add_variable(name, var, index) |
| 1761 |
# This could be avoided, but we currently need it so that standalone |
| 1762 |
# allocates the memory |
| 1763 |
self.device.init_with_zeros(var, dtype) |
| 1764 |
if values is not None: |
| 1765 |
if scalar: |
| 1766 |
if np.asanyarray(values).shape != (): |
| 1767 |
raise ValueError("Need a scalar value.") |
| 1768 |
self.device.fill_with_array(var, values) |
| 1769 |
else: |
| 1770 |
if len(values) != size: |
| 1771 |
raise ValueError( |
| 1772 |
"Size of the provided values does not match " |
| 1773 |
f"size: {len(values)} != {size}" |
| 1774 |
) |
| 1775 |
self.device.fill_with_array(var, values) |
| 1776 |
|
| 1777 |
def add_arrays( |
| 1778 |
self, |
| 1779 |
names, |
| 1780 |
size, |
| 1781 |
dimensions=DIMENSIONLESS, |
| 1782 |
dtype=None, |
| 1783 |
constant=False, |
| 1784 |
read_only=False, |
| 1785 |
scalar=False, |
| 1786 |
unique=False, |
| 1787 |
index=None, |
| 1788 |
): |
| 1789 |
""" |
| 1790 |
Adds several arrays (initialized with zeros) with the same attributes |
| 1791 |
(size, units, etc.). |
| 1792 |
|
| 1793 |
Parameters |
| 1794 |
---------- |
| 1795 |
names : list of str |
| 1796 |
The names of the variable. |
| 1797 |
dimensions : `Dimension`, optional |
| 1798 |
The physical dimensions of the variable. |
| 1799 |
size : int |
| 1800 |
The sizes of the arrays. |
| 1801 |
dtype : `dtype`, optional |
| 1802 |
The dtype used for storing the variables. If none is given, defaults |
| 1803 |
to `core.default_float_dtype`. |
| 1804 |
constant : bool, optional |
| 1805 |
Whether the variables' values are constant during a run. |
| 1806 |
Defaults to ``False``. |
| 1807 |
scalar : bool, optional |
| 1808 |
Whether these are scalar variables. Defaults to ``False``, if set to |
| 1809 |
``True``, also implies that `size` equals 1. |
| 1810 |
read_only : bool, optional |
| 1811 |
Whether these are read-only variables, i.e. variables that are set |
| 1812 |
internally and cannot be changed by the user. Defaults |
| 1813 |
to ``False``. |
| 1814 |
index : str, optional |
| 1815 |
The index to use for these variables. Defaults to |
| 1816 |
`Variables.default_index`. |
| 1817 |
unique : bool, optional |
| 1818 |
See `ArrayVariable`. Defaults to ``False``. |
| 1819 |
""" |
| 1820 |
for name in names: |
| 1821 |
self.add_array( |
| 1822 |
name, |
| 1823 |
dimensions=dimensions, |
| 1824 |
size=size, |
| 1825 |
dtype=dtype, |
| 1826 |
constant=constant, |
| 1827 |
read_only=read_only, |
| 1828 |
scalar=scalar, |
| 1829 |
unique=unique, |
| 1830 |
index=index, |
| 1831 |
) |
| 1832 |
|
| 1833 |
def add_dynamic_array( |
| 1834 |
self, |
| 1835 |
name, |
| 1836 |
size, |
| 1837 |
dimensions=DIMENSIONLESS, |
| 1838 |
values=None, |
| 1839 |
dtype=None, |
| 1840 |
constant=False, |
| 1841 |
needs_reference_update=False, |
| 1842 |
resize_along_first=False, |
| 1843 |
read_only=False, |
| 1844 |
unique=False, |
| 1845 |
scalar=False, |
| 1846 |
index=None, |
| 1847 |
): |
| 1848 |
""" |
| 1849 |
Add a dynamic array. |
| 1850 |
|
| 1851 |
Parameters |
| 1852 |
---------- |
| 1853 |
name : str |
| 1854 |
The name of the variable. |
| 1855 |
dimensions : `Dimension`, optional |
| 1856 |
The physical dimensions of the variable. |
| 1857 |
size : int or tuple of int |
| 1858 |
The (initital) size of the array. |
| 1859 |
values : `ndarray`, optional |
| 1860 |
The values to initalize the array with. If not specified, the array |
| 1861 |
is initialized to zero. |
| 1862 |
dtype : `dtype`, optional |
| 1863 |
The dtype used for storing the variable. If none is given, defaults |
| 1864 |
to `core.default_float_dtype`. |
| 1865 |
constant : bool, optional |
| 1866 |
Whether the variable's value is constant during a run. |
| 1867 |
Defaults to ``False``. |
| 1868 |
needs_reference_update : bool, optional |
| 1869 |
Whether the code objects need a new reference to the underlying data at |
| 1870 |
every time step. This should be set if the size of the array can be |
| 1871 |
changed by other code objects. Defaults to ``False``. |
| 1872 |
scalar : bool, optional |
| 1873 |
Whether this is a scalar variable. Defaults to ``False``, if set to |
| 1874 |
``True``, also implies that `size` equals 1. |
| 1875 |
read_only : bool, optional |
| 1876 |
Whether this is a read-only variable, i.e. a variable that is set |
| 1877 |
internally and cannot be changed by the user. Defaults |
| 1878 |
to ``False``. |
| 1879 |
index : str, optional |
| 1880 |
The index to use for this variable. Defaults to |
| 1881 |
`Variables.default_index`. |
| 1882 |
unique : bool, optional |
| 1883 |
See `DynamicArrayVariable`. Defaults to ``False``. |
| 1884 |
""" |
| 1885 |
var = DynamicArrayVariable( |
| 1886 |
name=name, |
| 1887 |
dimensions=dimensions, |
| 1888 |
owner=self.owner, |
| 1889 |
device=self.device, |
| 1890 |
size=size, |
| 1891 |
dtype=dtype, |
| 1892 |
constant=constant, |
| 1893 |
needs_reference_update=needs_reference_update, |
| 1894 |
resize_along_first=resize_along_first, |
| 1895 |
scalar=scalar, |
| 1896 |
read_only=read_only, |
| 1897 |
unique=unique, |
| 1898 |
) |
| 1899 |
self._add_variable(name, var, index) |
| 1900 |
if np.prod(size) > 0: |
| 1901 |
self.device.resize(var, size) |
| 1902 |
if values is None and np.prod(size) > 0: |
| 1903 |
self.device.init_with_zeros(var, dtype) |
| 1904 |
elif values is not None: |
| 1905 |
if len(values) != size: |
| 1906 |
raise ValueError( |
| 1907 |
"Size of the provided values does not match " |
| 1908 |
f"size: {len(values)} != {size}" |
| 1909 |
) |
| 1910 |
if np.prod(size) > 0: |
| 1911 |
self.device.fill_with_array(var, values) |
| 1912 |
|
| 1913 |
def add_arange( |
| 1914 |
self, |
| 1915 |
name, |
| 1916 |
size, |
| 1917 |
start=0, |
| 1918 |
dtype=np.int32, |
| 1919 |
constant=True, |
| 1920 |
read_only=True, |
| 1921 |
unique=True, |
| 1922 |
index=None, |
| 1923 |
): |
| 1924 |
""" |
| 1925 |
Add an array, initialized with a range of integers. |
| 1926 |
|
| 1927 |
Parameters |
| 1928 |
---------- |
| 1929 |
name : str |
| 1930 |
The name of the variable. |
| 1931 |
size : int |
| 1932 |
The size of the array. |
| 1933 |
start : int |
| 1934 |
The start value of the range. |
| 1935 |
dtype : `dtype`, optional |
| 1936 |
The dtype used for storing the variable. If none is given, defaults |
| 1937 |
to `np.int32`. |
| 1938 |
constant : bool, optional |
| 1939 |
Whether the variable's value is constant during a run. |
| 1940 |
Defaults to ``True``. |
| 1941 |
read_only : bool, optional |
| 1942 |
Whether this is a read-only variable, i.e. a variable that is set |
| 1943 |
internally and cannot be changed by the user. Defaults |
| 1944 |
to ``True``. |
| 1945 |
index : str, optional |
| 1946 |
The index to use for this variable. Defaults to |
| 1947 |
`Variables.default_index`. |
| 1948 |
unique : bool, optional |
| 1949 |
See `ArrayVariable`. Defaults to ``True`` here. |
| 1950 |
""" |
| 1951 |
self.add_array( |
| 1952 |
name=name, |
| 1953 |
dimensions=DIMENSIONLESS, |
| 1954 |
size=size, |
| 1955 |
dtype=dtype, |
| 1956 |
constant=constant, |
| 1957 |
read_only=read_only, |
| 1958 |
unique=unique, |
| 1959 |
index=index, |
| 1960 |
) |
| 1961 |
self.device.init_with_arange(self._variables[name], start, dtype=dtype) |
| 1962 |
|
| 1963 |
def add_constant(self, name, value, dimensions=DIMENSIONLESS): |
| 1964 |
""" |
| 1965 |
Add a scalar constant (e.g. the number of neurons `N`). |
| 1966 |
|
| 1967 |
Parameters |
| 1968 |
---------- |
| 1969 |
name : str |
| 1970 |
The name of the variable |
| 1971 |
value: reference to the variable value |
| 1972 |
The value of the constant. |
| 1973 |
dimensions : `Dimension`, optional |
| 1974 |
The physical dimensions of the variable. Note that the variable |
| 1975 |
itself (as referenced by value) should never have units attached. |
| 1976 |
""" |
| 1977 |
var = Constant(name=name, dimensions=dimensions, owner=self.owner, value=value) |
| 1978 |
self._add_variable(name, var) |
| 1979 |
|
| 1980 |
def add_subexpression( |
| 1981 |
self, name, expr, dimensions=DIMENSIONLESS, dtype=None, scalar=False, index=None |
| 1982 |
): |
| 1983 |
""" |
| 1984 |
Add a named subexpression. |
| 1985 |
|
| 1986 |
Parameters |
| 1987 |
---------- |
| 1988 |
name : str |
| 1989 |
The name of the subexpression. |
| 1990 |
dimensions : `Dimension` |
| 1991 |
The physical dimensions of the subexpression. |
| 1992 |
expr : str |
| 1993 |
The subexpression itself. |
| 1994 |
dtype : `dtype`, optional |
| 1995 |
The dtype used for the expression. Defaults to |
| 1996 |
`core.default_float_dtype`. |
| 1997 |
scalar : bool, optional |
| 1998 |
Whether this is an expression only referring to scalar variables. |
| 1999 |
Defaults to ``False`` |
| 2000 |
index : str, optional |
| 2001 |
The index to use for this variable. Defaults to |
| 2002 |
`Variables.default_index`. |
| 2003 |
""" |
| 2004 |
var = Subexpression( |
| 2005 |
name=name, |
| 2006 |
dimensions=dimensions, |
| 2007 |
expr=expr, |
| 2008 |
owner=self.owner, |
| 2009 |
dtype=dtype, |
| 2010 |
device=self.device, |
| 2011 |
scalar=scalar, |
| 2012 |
) |
| 2013 |
self._add_variable(name, var, index=index) |
| 2014 |
|
| 2015 |
def add_auxiliary_variable( |
| 2016 |
self, name, dimensions=DIMENSIONLESS, dtype=None, scalar=False |
| 2017 |
): |
| 2018 |
""" |
| 2019 |
Add an auxiliary variable (most likely one that is added automatically |
| 2020 |
to abstract code, e.g. ``_cond`` for a threshold condition), |
| 2021 |
specifying its type and unit for code generation. |
| 2022 |
|
| 2023 |
Parameters |
| 2024 |
---------- |
| 2025 |
name : str |
| 2026 |
The name of the variable |
| 2027 |
dimensions : `Dimension` |
| 2028 |
The physical dimensions of the variable. |
| 2029 |
dtype : `dtype`, optional |
| 2030 |
The dtype used for storing the variable. If none is given, defaults |
| 2031 |
to `core.default_float_dtype`. |
| 2032 |
scalar : bool, optional |
| 2033 |
Whether the variable is a scalar value (``True``) or vector-valued, |
| 2034 |
e.g. defined for every neuron (``False``). Defaults to ``False``. |
| 2035 |
""" |
| 2036 |
var = AuxiliaryVariable( |
| 2037 |
name=name, dimensions=dimensions, dtype=dtype, scalar=scalar |
| 2038 |
) |
| 2039 |
self._add_variable(name, var) |
| 2040 |
|
| 2041 |
def add_referred_subexpression(self, name, group, subexpr, index): |
| 2042 |
identifiers = subexpr.identifiers |
| 2043 |
substitutions = {} |
| 2044 |
for identifier in identifiers: |
| 2045 |
if identifier not in subexpr.owner.variables: |
| 2046 |
# external variable --> nothing to do |
| 2047 |
continue |
| 2048 |
subexpr_var = subexpr.owner.variables[identifier] |
| 2049 |
if hasattr(subexpr_var, "owner"): |
| 2050 |
new_name = f"_{name}_{subexpr.owner.name}_{identifier}" |
| 2051 |
else: |
| 2052 |
new_name = f"_{name}_{identifier}" |
| 2053 |
substitutions[identifier] = new_name |
| 2054 |
|
| 2055 |
subexpr_var_index = group.variables.indices[identifier] |
| 2056 |
if subexpr_var_index == group.variables.default_index: |
| 2057 |
subexpr_var_index = index |
| 2058 |
elif subexpr_var_index == "0": |
| 2059 |
pass # nothing to do for a shared variable |
| 2060 |
elif subexpr_var_index == index: |
| 2061 |
pass # The same index as the main subexpression |
| 2062 |
elif index != self.default_index: |
| 2063 |
index_var = self._variables.get(index, None) |
| 2064 |
if isinstance(index_var, DynamicArrayVariable): |
| 2065 |
raise TypeError( |
| 2066 |
f"Cannot link to subexpression '{name}': it refers " |
| 2067 |
f"to the variable '{identifier}' which is indexed " |
| 2068 |
f"with the dynamic index '{subexpr_var_index}'." |
| 2069 |
) |
| 2070 |
else: |
| 2071 |
self.add_reference(subexpr_var_index, group) |
| 2072 |
|
| 2073 |
self.indices[new_name] = subexpr_var_index |
| 2074 |
|
| 2075 |
if isinstance(subexpr_var, Subexpression): |
| 2076 |
self.add_referred_subexpression( |
| 2077 |
new_name, group, subexpr_var, subexpr_var_index |
| 2078 |
) |
| 2079 |
else: |
| 2080 |
self.add_reference(new_name, group, identifier, subexpr_var_index) |
| 2081 |
|
| 2082 |
new_expr = word_substitute(subexpr.expr, substitutions) |
| 2083 |
new_subexpr = Subexpression( |
| 2084 |
name, |
| 2085 |
self.owner, |
| 2086 |
new_expr, |
| 2087 |
dimensions=subexpr.dim, |
| 2088 |
device=subexpr.device, |
| 2089 |
dtype=subexpr.dtype, |
| 2090 |
scalar=subexpr.scalar, |
| 2091 |
) |
| 2092 |
self._variables[name] = new_subexpr |
| 2093 |
|
| 2094 |
def add_reference(self, name, group, varname=None, index=None): |
| 2095 |
""" |
| 2096 |
Add a reference to a variable defined somewhere else (possibly under |
| 2097 |
a different name). This is for example used in `Subgroup` and |
| 2098 |
`Synapses` to refer to variables in the respective `NeuronGroup`. |
| 2099 |
|
| 2100 |
Parameters |
| 2101 |
---------- |
| 2102 |
name : str |
| 2103 |
The name of the variable (in this group, possibly a different name |
| 2104 |
from `var.name`). |
| 2105 |
group : `Group` |
| 2106 |
The group from which `var` is referenced |
| 2107 |
varname : str, optional |
| 2108 |
The variable to refer to. If not given, defaults to `name`. |
| 2109 |
index : str, optional |
| 2110 |
The index that should be used for this variable (defaults to |
| 2111 |
`Variables.default_index`). |
| 2112 |
""" |
| 2113 |
if varname is None: |
| 2114 |
varname = name |
| 2115 |
if varname not in group.variables: |
| 2116 |
raise KeyError(f"Group {group.name} does not have a variable {varname}.") |
| 2117 |
if index is None: |
| 2118 |
if group.variables[varname].scalar: |
| 2119 |
index = "0" |
| 2120 |
else: |
| 2121 |
index = self.default_index |
| 2122 |
|
| 2123 |
if ( |
| 2124 |
self.owner is not None |
| 2125 |
and self.owner.name != group.name |
| 2126 |
and index in self.owner.variables |
| 2127 |
): |
| 2128 |
if ( |
| 2129 |
not self.owner.variables[index].read_only |
| 2130 |
or isinstance(self.owner.variables[index], DynamicArrayVariable) |
| 2131 |
) and group.variables.indices[varname] != group.variables.default_index: |
| 2132 |
raise TypeError( |
| 2133 |
f"Cannot link variable '{name}' to '{varname}' in " |
| 2134 |
f"group '{group.name}' -- need to precalculate " |
| 2135 |
f"direct indices but index {index} can change" |
| 2136 |
) |
| 2137 |
|
| 2138 |
# We don't overwrite existing names with references |
| 2139 |
if name not in self._variables: |
| 2140 |
var = group.variables[varname] |
| 2141 |
if isinstance(var, Subexpression): |
| 2142 |
self.add_referred_subexpression(name, group, var, index) |
| 2143 |
else: |
| 2144 |
self._variables[name] = var |
| 2145 |
self.indices[name] = index |
| 2146 |
|
| 2147 |
def add_references(self, group, varnames, index=None): |
| 2148 |
""" |
| 2149 |
Add all `Variable` objects from a name to `Variable` mapping with the |
| 2150 |
same name as in the original mapping. |
| 2151 |
|
| 2152 |
Parameters |
| 2153 |
---------- |
| 2154 |
group : `Group` |
| 2155 |
The group from which the `variables` are referenced |
| 2156 |
varnames : iterable of str |
| 2157 |
The variables that should be referred to in the current group |
| 2158 |
index : str, optional |
| 2159 |
The index to use for all the variables (defaults to |
| 2160 |
`Variables.default_index`) |
| 2161 |
""" |
| 2162 |
for name in varnames: |
| 2163 |
self.add_reference(name, group, name, index) |
| 2164 |
|
| 2165 |
def add_object(self, name, obj): |
| 2166 |
""" |
| 2167 |
Add an arbitrary Python object. This is only meant for internal use |
| 2168 |
and therefore only names starting with an underscore are allowed. |
| 2169 |
|
| 2170 |
Parameters |
| 2171 |
---------- |
| 2172 |
name : str |
| 2173 |
The name used for this object (has to start with an underscore). |
| 2174 |
obj : object |
| 2175 |
An arbitrary Python object that needs to be accessed directly from |
| 2176 |
a `CodeObject`. |
| 2177 |
""" |
| 2178 |
if not name.startswith("_"): |
| 2179 |
raise ValueError( |
| 2180 |
"This method is only meant for internally used " |
| 2181 |
"objects, the name therefore has to start with " |
| 2182 |
"an underscore" |
| 2183 |
) |
| 2184 |
self._variables[name] = obj |
| 2185 |
|
| 2186 |
def create_clock_variables(self, clock, prefix=""): |
| 2187 |
""" |
| 2188 |
Convenience function to add the ``t`` and ``dt`` (or ``times``, for |
| 2189 |
an `EventClock`) attributes of a `clock`. |
| 2190 |
|
| 2191 |
Parameters |
| 2192 |
---------- |
| 2193 |
clock : `BaseClock` |
| 2194 |
The clock that should be used for ``t`` and ``dt`` or ``times``. |
| 2195 |
prefix : str, optional |
| 2196 |
A prefix for the variable names. Used for example in monitors to |
| 2197 |
not confuse the dynamic array of recorded times with the current |
| 2198 |
time in the recorded group. |
| 2199 |
""" |
| 2200 |
from brian2.core.clocks import Clock # avoid circular import |
| 2201 |
|
| 2202 |
self.add_reference(f"{prefix}t", clock, "t") |
| 2203 |
if isinstance(clock, Clock): |
| 2204 |
self.add_reference(f"{prefix}dt", clock, "dt") |
| 2205 |
self.add_reference(f"{prefix}t_in_timesteps", clock, "timestep") |
| 2206 |
else: |
| 2207 |
self.add_reference(f"{prefix}times", clock, "times") |