/
variables.py
2157 lines (1908 loc) · 76.1 KB
/
variables.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Classes used to specify the type of a function, variable or common
sub-expression.
"""
import collections
import functools
import numbers
from collections.abc import Mapping
import numpy as np
from brian2.units.fundamentalunits import (
DIMENSIONLESS,
Dimension,
Quantity,
fail_for_dimension_mismatch,
get_unit,
get_unit_for_display,
)
from brian2.utils.caching import CacheKey
from brian2.utils.logger import get_logger
from brian2.utils.stringtools import get_identifiers, word_substitute
from .base import device_override, weakproxy_with_fallback
from .preferences import prefs
__all__ = [
"Variable",
"Constant",
"ArrayVariable",
"DynamicArrayVariable",
"Subexpression",
"AuxiliaryVariable",
"VariableView",
"Variables",
"LinkedVariable",
"linked_var",
]
logger = get_logger(__name__)
def get_dtype(obj):
"""
Helper function to return the `numpy.dtype` of an arbitrary object.
Parameters
----------
obj : object
Any object (but typically some kind of number or array).
Returns
-------
dtype : `numpy.dtype`
The type of the given object.
"""
if hasattr(obj, "dtype"):
return obj.dtype
else:
return np.dtype(type(obj))
def get_dtype_str(val):
"""
Returns canonical string representation of the dtype of a value or dtype
Returns
-------
dtype_str : str
The numpy dtype name
"""
if isinstance(val, np.dtype):
return val.name
if isinstance(val, type):
return get_dtype_str(val())
is_bool = val is True or val is False or val is np.True_ or val is np.False_
if is_bool:
return "bool"
if hasattr(val, "dtype"):
return get_dtype_str(val.dtype)
if isinstance(val, numbers.Number):
return get_dtype_str(np.array(val).dtype)
return f"unknown[{str(val)}, {val.__class__.__name__}]"
def variables_by_owner(variables, owner):
owner_name = getattr(owner, "name", None)
return {
varname: var
for varname, var in variables.items()
if getattr(var.owner, "name", None) is owner_name
}
class Variable(CacheKey):
r"""
An object providing information about model variables (including implicit
variables such as ``t`` or ``xi``). This class should never be
instantiated outside of testing code, use one of its subclasses instead.
Parameters
----------
name : 'str'
The name of the variable. Note that this refers to the *original*
name in the owning group. The same variable may be known under other
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is
known as ``v_post`` in a `Synapse` connecting to the group).
dimensions : `Dimension`, optional
The physical dimensions of the variable.
owner : `Nameable`, optional
The object that "owns" this variable, e.g. the `NeuronGroup` or
`Synapses` object that declares the variable in its model equations.
Defaults to ``None`` (the value used for `Variable` objects without an
owner, e.g. external `Constant`\ s).
dtype : `dtype`, optional
The dtype used for storing the variable. Defaults to the preference
`core.default_scalar.dtype`.
scalar : bool, optional
Whether the variable is a scalar value (``True``) or vector-valued, e.g.
defined for every neuron (``False``). Defaults to ``False``.
constant: bool, optional
Whether the value of this variable can change during a run. Defaults
to ``False``.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user (this is used for example
for the variable ``N``, the number of neurons in a group). Defaults
to ``False``.
array : bool, optional
Whether this variable is an array. Allows for simpler check than testing
``isinstance(var, ArrayVariable)``. Defaults to ``False``.
"""
_cache_irrelevant_attributes = {"owner"}
def __init__(
self,
name,
dimensions=DIMENSIONLESS,
owner=None,
dtype=None,
scalar=False,
constant=False,
read_only=False,
dynamic=False,
array=False,
):
assert isinstance(dimensions, Dimension)
#: The variable's dimensions.
self.dim = dimensions
#: The variable's name.
self.name = name
#: The `Group` to which this variable belongs.
self.owner = weakproxy_with_fallback(owner) if owner is not None else None
#: The dtype used for storing the variable.
self.dtype = dtype
if dtype is None:
self.dtype = prefs.core.default_float_dtype
if self.is_boolean:
if dimensions is not DIMENSIONLESS:
raise ValueError("Boolean variables can only be dimensionless")
#: Whether the variable is a scalar
self.scalar = scalar
#: Whether the variable is constant during a run
self.constant = constant
#: Whether the variable is read-only
self.read_only = read_only
#: Whether the variable is dynamically sized (only for non-scalars)
self.dynamic = dynamic
#: Whether the variable is an array
self.array = array
def __getstate__(self):
state = self.__dict__.copy()
state["owner"] = state["owner"].__repr__.__self__ # replace proxy
return state
def __setstate__(self, state):
state["owner"] = weakproxy_with_fallback(state["owner"])
self.__dict__ = state
@property
def is_boolean(self):
return np.issubdtype(self.dtype, np.bool_)
@property
def is_integer(self):
return np.issubdtype(self.dtype, np.signedinteger)
@property
def dtype_str(self):
"""
String representation of the numpy dtype
"""
return get_dtype_str(self)
@property
def unit(self):
"""
The `Unit` of this variable
"""
return get_unit(self.dim)
def get_value(self):
"""
Return the value associated with the variable (without units). This
is the way variables are accessed in generated code.
"""
raise TypeError(f"Cannot get value for variable {self}")
def set_value(self, value):
"""
Set the value associated with the variable.
"""
raise TypeError(f"Cannot set value for variable {self}")
def get_value_with_unit(self):
"""
Return the value associated with the variable (with units).
"""
return Quantity(self.get_value(), self.dim)
def get_addressable_value(self, name, group):
"""
Get the value (without units) of this variable in a form that can be
indexed in the context of a group. For example, if a
postsynaptic variable ``x`` is accessed in a synapse ``S`` as
``S.x_post``, the synaptic indexing scheme can be used.
Parameters
----------
name : str
The name of the variable
group : `Group`
The group providing the context for the indexing. Note that this
`group` is not necessarily the same as `Variable.owner`: a variable
owned by a `NeuronGroup` can be indexed in a different way if
accessed via a `Synapses` object.
Returns
-------
variable : object
The variable in an indexable form (without units).
"""
return self.get_value()
def get_addressable_value_with_unit(self, name, group):
"""
Get the value (with units) of this variable in a form that can be
indexed in the context of a group. For example, if a postsynaptic
variable ``x`` is accessed in a synapse ``S`` as ``S.x_post``, the
synaptic indexing scheme can be used.
Parameters
----------
name : str
The name of the variable
group : `Group`
The group providing the context for the indexing. Note that this
`group` is not necessarily the same as `Variable.owner`: a variable
owned by a `NeuronGroup` can be indexed in a different way if
accessed via a `Synapses` object.
Returns
-------
variable : object
The variable in an indexable form (with units).
"""
return self.get_value_with_unit()
def get_len(self):
"""
Get the length of the value associated with the variable or ``0`` for
a scalar variable.
"""
if self.scalar:
return 0
else:
return len(self.get_value())
def __len__(self):
return self.get_len()
def __repr__(self):
description = (
"<{classname}(dimensions={dimensions}, "
" dtype={dtype}, scalar={scalar}, constant={constant},"
" read_only={read_only})>"
)
return description.format(
classname=self.__class__.__name__,
dimensions=repr(self.dim),
dtype=getattr(self.dtype, "__name__", repr(self.dtype)),
scalar=repr(self.scalar),
constant=repr(self.constant),
read_only=repr(self.read_only),
)
# ------------------------------------------------------------------------------
# Concrete classes derived from `Variable` -- these are the only ones ever
# instantiated.
# ------------------------------------------------------------------------------
class Constant(Variable):
"""
A scalar constant (e.g. the number of neurons ``N``). Information such as
the dtype or whether this variable is a boolean are directly derived from
the `value`. Most of the time `Variables.add_constant` should be used
instead of instantiating this class directly.
Parameters
----------
name : str
The name of the variable
dimensions : `Dimension`, optional
The physical dimensions of the variable. Note that the variable itself
(as referenced by value) should never have units attached.
value: reference to the variable value
The value of the constant.
owner : `Nameable`, optional
The object that "owns" this variable, for constants that belong to a
specific group, e.g. the ``N`` constant for a `NeuronGroup`. External
constants will have ``None`` (the default value).
"""
def __init__(self, name, value, dimensions=DIMENSIONLESS, owner=None):
# Determine the type of the value
is_bool = (
value is True or value is False or value is np.True_ or value is np.False_
)
if is_bool:
dtype = bool
else:
dtype = get_dtype(value)
# Use standard Python types if possible for numpy scalars
if getattr(value, "shape", None) == () and hasattr(value, "dtype"):
numpy_type = value.dtype
if np.can_cast(numpy_type, int):
value = int(value)
elif np.can_cast(numpy_type, float):
value = float(value)
elif np.can_cast(numpy_type, complex):
value = complex(value)
elif value is np.True_:
value = True
elif value is np.False_:
value = False
#: The constant's value
self.value = value
super().__init__(
dimensions=dimensions,
name=name,
owner=owner,
dtype=dtype,
scalar=True,
constant=True,
read_only=True,
)
def get_value(self):
return self.value
def item(self):
return self.value
class AuxiliaryVariable(Variable):
"""
Variable description for an auxiliary variable (most likely one that is
added automatically to abstract code, e.g. ``_cond`` for a threshold
condition), specifying its type and unit for code generation. Most of the
time `Variables.add_auxiliary_variable` should be used instead of
instantiating this class directly.
Parameters
----------
name : str
The name of the variable
dimensions : `Dimension`, optional
The physical dimensions of the variable.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
scalar : bool, optional
Whether the variable is a scalar value (``True``) or vector-valued, e.g.
defined for every neuron (``False``). Defaults to ``False``.
"""
def __init__(self, name, dimensions=DIMENSIONLESS, dtype=None, scalar=False):
super().__init__(dimensions=dimensions, name=name, dtype=dtype, scalar=scalar)
def get_value(self):
raise TypeError(
f"Cannot get the value for an auxiliary variable ({self.name})."
)
class ArrayVariable(Variable):
"""
An object providing information about a model variable stored in an array
(for example, all state variables). Most of the time `Variables.add_array`
should be used instead of instantiating this class directly.
Parameters
----------
name : 'str'
The name of the variable. Note that this refers to the *original*
name in the owning group. The same variable may be known under other
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is
known as ``v_post`` in a `Synapse` connecting to the group).
dimensions : `Dimension`, optional
The physical dimensions of the variable
owner : `Nameable`
The object that "owns" this variable, e.g. the `NeuronGroup` or
`Synapses` object that declares the variable in its model equations.
size : int
The size of the array
device : `Device`
The device responsible for the memory access.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
constant : bool, optional
Whether the variable's value is constant during a run.
Defaults to ``False``.
scalar : bool, optional
Whether this array is a 1-element array that should be treated like a
scalar (e.g. for a single delay value across synapses). Defaults to
``False``.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user. Defaults
to ``False``.
unique : bool, optional
Whether the values in this array are all unique. This information is
only important for variables used as indices and does not have to
reflect the actual contents of the array but only the possibility of
non-uniqueness (e.g. synaptic indices are always unique but the
corresponding pre- and post-synaptic indices are not). Defaults to
``False``.
"""
def __init__(
self,
name,
owner,
size,
device,
dimensions=DIMENSIONLESS,
dtype=None,
constant=False,
scalar=False,
read_only=False,
dynamic=False,
unique=False,
):
super().__init__(
dimensions=dimensions,
name=name,
owner=owner,
dtype=dtype,
scalar=scalar,
constant=constant,
read_only=read_only,
dynamic=dynamic,
array=True,
)
#: Wether all values in this arrays are necessarily unique (only
#: relevant for index variables).
self.unique = unique
#: The `Device` responsible for memory access.
self.device = device
#: The size of this variable.
self.size = size
if scalar and size != 1:
raise ValueError(f"Scalar variables need to have size 1, not size {size}.")
#: Another variable, on which the write is conditioned (e.g. a variable
#: denoting the absence of refractoriness)
self.conditional_write = None
def set_conditional_write(self, var):
if not var.is_boolean:
raise TypeError(
"A variable can only be conditionally writeable "
f"depending on a boolean variable, '{var.name}' is not "
"boolean."
)
self.conditional_write = var
def get_value(self):
return self.device.get_value(self)
def item(self):
if self.size == 1:
return self.get_value().item()
else:
raise ValueError("can only convert an array of size 1 to a Python scalar")
def set_value(self, value):
self.device.fill_with_array(self, value)
def get_len(self):
return self.size
def get_addressable_value(self, name, group):
return VariableView(name=name, variable=self, group=group, dimensions=None)
def get_addressable_value_with_unit(self, name, group):
return VariableView(name=name, variable=self, group=group, dimensions=self.dim)
class DynamicArrayVariable(ArrayVariable):
"""
An object providing information about a model variable stored in a dynamic
array (used in `Synapses`). Most of the time `Variables.add_dynamic_array`
should be used instead of instantiating this class directly.
Parameters
----------
name : 'str'
The name of the variable. Note that this refers to the *original*
name in the owning group. The same variable may be known under other
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is
known as ``v_post`` in a `Synapse` connecting to the group).
dimensions : `Dimension`, optional
The physical dimensions of the variable.
owner : `Nameable`
The object that "owns" this variable, e.g. the `NeuronGroup` or
`Synapses` object that declares the variable in its model equations.
size : int or tuple of int
The (initial) size of the variable.
device : `Device`
The device responsible for the memory access.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
constant : bool, optional
Whether the variable's value is constant during a run.
Defaults to ``False``.
needs_reference_update : bool, optional
Whether the code objects need a new reference to the underlying data at
every time step. This should be set if the size of the array can be
changed by other code objects. Defaults to ``False``.
scalar : bool, optional
Whether this array is a 1-element array that should be treated like a
scalar (e.g. for a single delay value across synapses). Defaults to
``False``.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user. Defaults
to ``False``.
unique : bool, optional
Whether the values in this array are all unique. This information is
only important for variables used as indices and does not have to
reflect the actual contents of the array but only the possibility of
non-uniqueness (e.g. synaptic indices are always unique but the
corresponding pre- and post-synaptic indices are not). Defaults to
``False``.
"""
# The size of a dynamic variable can of course change and changes in
# size should not invalidate the cache
_cache_irrelevant_attributes = ArrayVariable._cache_irrelevant_attributes | {"size"}
def __init__(
self,
name,
owner,
size,
device,
dimensions=DIMENSIONLESS,
dtype=None,
constant=False,
needs_reference_update=False,
resize_along_first=False,
scalar=False,
read_only=False,
unique=False,
):
if isinstance(size, int):
ndim = 1
else:
ndim = len(size)
#: The number of dimensions
self.ndim = ndim
if constant and needs_reference_update:
raise ValueError("A variable cannot be constant and need reference updates")
#: Whether this variable needs an update of the reference to the
#: underlying data whenever it is passed to a code object
self.needs_reference_update = needs_reference_update
#: Whether this array will be only resized along the first dimension
self.resize_along_first = resize_along_first
super().__init__(
dimensions=dimensions,
owner=owner,
name=name,
size=size,
device=device,
constant=constant,
dtype=dtype,
scalar=scalar,
dynamic=True,
read_only=read_only,
unique=unique,
)
@property
def dimensions(self):
logger.warn(
"The DynamicArrayVariable.dimensions attribute is "
"deprecated, use .ndim instead",
"deprecated_dimensions",
once=True,
)
return self.ndim
def resize(self, new_size):
"""
Resize the dynamic array. Calls `self.device.resize` to do the
actual resizing.
Parameters
----------
new_size : int or tuple of int
The new size.
"""
if self.resize_along_first:
self.device.resize_along_first(self, new_size)
else:
self.device.resize(self, new_size)
self.size = new_size
class Subexpression(Variable):
"""
An object providing information about a named subexpression in a model.
Most of the time `Variables.add_subexpression` should be used instead of
instantiating this class directly.
Parameters
----------
name : str
The name of the subexpression.
dimensions : `Dimension`, optional
The physical dimensions of the subexpression.
owner : `Group`
The group to which the expression refers.
expr : str
The subexpression itself.
device : `Device`
The device responsible for the memory access.
dtype : `dtype`, optional
The dtype used for the expression. Defaults to
`core.default_float_dtype`.
scalar: bool, optional
Whether this is an expression only referring to scalar variables.
Defaults to ``False``
"""
def __init__(
self,
name,
owner,
expr,
device,
dimensions=DIMENSIONLESS,
dtype=None,
scalar=False,
):
super().__init__(
dimensions=dimensions,
owner=owner,
name=name,
dtype=dtype,
scalar=scalar,
constant=False,
read_only=True,
)
#: The `Device` responsible for memory access
self.device = device
#: The expression defining the subexpression
self.expr = expr.strip()
#: The identifiers used in the expression
self.identifiers = get_identifiers(expr)
def get_addressable_value(self, name, group):
return VariableView(
name=name, variable=self, group=group, dimensions=DIMENSIONLESS
)
def get_addressable_value_with_unit(self, name, group):
return VariableView(name=name, variable=self, group=group, dimensions=self.dim)
def __contains__(self, var):
return var in self.identifiers
def __repr__(self):
description = (
"<{classname}(name={name}, dimensions={dimensions}, dtype={dtype}, "
"expr={expr}, owner=<{owner}>)>"
)
return description.format(
classname=self.__class__.__name__,
name=repr(self.name),
dimensions=repr(self.dim),
dtype=repr(self.dtype),
expr=repr(self.expr),
owner=self.owner.name,
)
# ------------------------------------------------------------------------------
# Classes providing views on variables and storing variables information
# ------------------------------------------------------------------------------
class LinkedVariable:
"""
A simple helper class to make linking variables explicit. Users should use
`linked_var` instead.
Parameters
----------
group : `Group`
The group through which the `variable` is accessed (not necessarily the
same as ``variable.owner``.
name : str
The name of `variable` in `group` (not necessarily the same as
``variable.name``).
variable : `Variable`
The variable that should be linked.
index : str or `ndarray`, optional
An indexing array (or the name of a state variable), providing a mapping
from the entries in the link source to the link target.
"""
def __init__(self, group, name, variable, index=None):
self.group = group
self.name = name
self.variable = variable
self.index = index
def linked_var(group_or_variable, name=None, index=None):
"""
Represents a link target for setting a linked variable.
Parameters
----------
group_or_variable : `NeuronGroup` or `VariableView`
Either a reference to the target `NeuronGroup` (e.g. ``G``) or a direct
reference to a `VariableView` object (e.g. ``G.v``). In case only the
group is specified, `name` has to be specified as well.
name : str, optional
The name of the target variable, necessary if `group_or_variable` is a
`NeuronGroup`.
index : str or `ndarray`, optional
An indexing array (or the name of a state variable), providing a mapping
from the entries in the link source to the link target.
Examples
--------
>>> from brian2 import *
>>> G1 = NeuronGroup(10, 'dv/dt = -v / (10*ms) : volt')
>>> G2 = NeuronGroup(10, 'v : volt (linked)')
>>> G2.v = linked_var(G1, 'v')
>>> G2.v = linked_var(G1.v) # equivalent
"""
if isinstance(group_or_variable, VariableView):
if name is not None:
raise ValueError(
"Cannot give a variable and a variable name at the same time."
)
return LinkedVariable(
group_or_variable.group,
group_or_variable.name,
group_or_variable.variable,
index=index,
)
elif name is None:
raise ValueError("Need to provide a variable name")
else:
return LinkedVariable(
group_or_variable, name, group_or_variable.variables[name], index=index
)
class VariableView:
"""
A view on a variable that allows to treat it as an numpy array while
allowing special indexing (e.g. with strings) in the context of a `Group`.
Parameters
----------
name : str
The name of the variable (not necessarily the same as ``variable.name``).
variable : `Variable`
The variable description.
group : `Group`
The group through which the variable is accessed (not necessarily the
same as `variable.owner`).
dimensions : `Dimension`, optional
The physical dimensions to be used for the variable, should be `None`
when a variable is accessed without units (e.g. when accessing
``G.var_``).
"""
__array_priority__ = 10
def __init__(self, name, variable, group, dimensions=None):
self.name = name
self.variable = variable
self.index_var_name = group.variables.indices[name]
if self.index_var_name in ("_idx", "0"):
self.index_var = self.index_var_name
else:
self.index_var = group.variables[self.index_var_name]
if isinstance(variable, Subexpression):
# For subexpressions, we *always* have to go via codegen to get
# their value -- since we cannot do this without the group, we
# hold a strong reference
self.group = group
else:
# For state variable arrays, we can do most access without the full
# group, using the indexing reference below. We therefore only keep
# a weak reference to the group.
self.group = weakproxy_with_fallback(group)
self.group_name = group.name
# We keep a strong reference to the `Indexing` object so that basic
# indexing is still possible, even if the group no longer exists
self.indexing = self.group._indices
self.dim = dimensions
@property
def unit(self):
"""
The `Unit` of this variable
"""
return get_unit(self.dim)
def get_item(self, item, level=0, namespace=None):
"""
Get the value of this variable. Called by `__getitem__`.
Parameters
----------
item : slice, `ndarray` or string
The index for the setting operation
level : int, optional
How much farther to go up in the stack to find the implicit
namespace (if used, see `run_namespace`).
namespace : dict-like, optional
An additional namespace that is used for variable lookup (if not
defined, the implicit namespace of local variables is used).
"""
from brian2.core.namespace import get_local_namespace # avoids circular import
if isinstance(item, str):
# Check whether the group still exists to give a more meaningful
# error message if it does not
try:
self.group.name
except ReferenceError:
raise ReferenceError(
"Cannot use string expressions, the "
f"group '{self.group_name}', providing the "
"context for the expression, no longer exists. "
"Consider holding an explicit reference "
"to it to keep it alive."
)
if namespace is None:
namespace = get_local_namespace(level=level + 1)
values = self.get_with_expression(item, run_namespace=namespace)
else:
if isinstance(self.variable, Subexpression):
if namespace is None:
namespace = get_local_namespace(level=level + 1)
values = self.get_subexpression_with_index_array(
item, run_namespace=namespace
)
else:
values = self.get_with_index_array(item)
if self.dim is DIMENSIONLESS or self.dim is None:
return values
else:
return Quantity(values, self.dim)
def __getitem__(self, item):
return self.get_item(item, level=1)
def set_item(self, item, value, level=0, namespace=None):
"""
Set this variable. This function is called by `__setitem__` but there
is also a situation where it should be called directly: if the context
for string-based expressions is higher up in the stack, this function
allows to set the `level` argument accordingly.
Parameters
----------
item : slice, `ndarray` or string
The index for the setting operation
value : `Quantity`, `ndarray` or number
The value for the setting operation
level : int, optional
How much farther to go up in the stack to find the implicit
namespace (if used, see `run_namespace`).
namespace : dict-like, optional
An additional namespace that is used for variable lookup (if not
defined, the implicit namespace of local variables is used).
"""
from brian2.core.namespace import get_local_namespace # avoids circular import
variable = self.variable
if variable.read_only:
raise TypeError(f"Variable {self.name} is read-only.")
# Check whether the group allows writing to the variable (e.g. for
# synaptic variables, writing is only allowed after a connect)
try:
self.group.check_variable_write(variable)
except ReferenceError:
# Ignore problems with weakly referenced groups that don't exist
# anymore at this time (e.g. when doing neuron.axon.var = ...)
pass
# The second part is equivalent to item == slice(None) but formulating
# it this way prevents a FutureWarning if one of the elements is a
# numpy array
if isinstance(item, slice) and (
item.start is None and item.stop is None and item.step is None
):
item = "True"
check_units = self.dim is not None
if namespace is None:
namespace = get_local_namespace(level=level + 1)
# Both index and values are strings, use a single code object do deal
# with this situation
if isinstance(value, str) and isinstance(item, str):
self.set_with_expression_conditional(
item, value, check_units=check_units, run_namespace=namespace
)
elif isinstance(item, str):
try:
if isinstance(value, str):
raise TypeError # Will be dealt with below
value = np.asanyarray(value).item()
except (TypeError, ValueError):
if item != "True":
raise TypeError(
"When setting a variable based on a string "
"index, the value has to be a string or a "
"scalar."
)
if item == "True":
# We do not want to go through code generation for runtime
self.set_with_index_array(slice(None), value, check_units=check_units)
else:
self.set_with_expression_conditional(
item, repr(value), check_units=check_units, run_namespace=namespace
)
elif isinstance(value, str):
self.set_with_expression(