Debian Codegraph @

docs_sphinx/developer/variables_indices.rst

raw
1 Variables and indices
2 =====================
3
4 Introduction
5 ------------
6 To be able to generate the proper code out of abstract code statements, the code
7 generation process has to have access to information about the variables (their
8 type, size, etc.) as well as to the indices that should be used for indexing
9 arrays (e.g. a state variable of a `NeuronGroup` will be indexed differently in
10 the `NeuronGroup` state updater and in synaptic propagation code). Most of this
11 information is stored in the `variables` attribute of a `VariableOwner` (this
12 includes `NeuronGroup`, `Synapses`, `PoissonGroup` and everything else that has
13 state variables). The `variables` attribute can be accessed as a (read-only)
14 dictionary, mapping variable names to `Variable` objects storing the
15 information about the respective variable. However, it is not a simple
16 dictionary but an instance of the `Variables` class. Let's have a look at its
17 content for a simple example::
18
19 >>> tau = 10*ms
20 >>> G = NeuronGroup(10, 'dv/dt = -v / tau : volt')
21 >>> for name, var in sorted(G.variables.items()):
22 ... print('%s : %s' % (name, var)) # doctest: +SKIP
23 ...
24 N : <Constant(dimensions=Dimension(), dtype=int64, scalar=True, constant=True, read_only=True)>
25 dt : <ArrayVariable(dimensions=second, dtype=float, scalar=True, constant=True, read_only=True)>
26 i : <ArrayVariable(dimensions=Dimension(), dtype=int32, scalar=False, constant=True, read_only=True)>
27 t : <ArrayVariable(dimensions=second, dtype=float64, scalar=True, constant=False, read_only=True)>
28 t_in_timesteps : <ArrayVariable(dimensions=Dimension(), dtype=int64, scalar=True, constant=False, read_only=True)>
29 v : <ArrayVariable(dimensions=metre ** 2 * kilogram * second ** -3 * amp ** -1, dtype=float64, scalar=False, constant=False, read_only=False)>
30
31 The state variable ``v`` we specified for the `NeuronGroup` is represented as an
32 `ArrayVariable`, all the other variables were added automatically. There's another array ``i``, the
33 neuronal indices (simply an array of integers from 0 to 9), that is used for
34 string expressions involving neuronal indices. The constant ``N`` represents
35 the total number of neurons. At the first sight it might be surprising that
36 ``t``, the current time of the clock and ``dt``, its timestep, are
37 `ArrayVariable` objects as well. This is because those values can change during
38 a run (for ``t``) or between runs (for ``dt``), and storing them as arrays with
39 a single value (note the ``scalar=True``) is the easiest way to share this value
40 -- all code accessing it only needs a reference to the array and can access its
41 only element.
42
43 The information stored in the `Variable` objects is used to do various checks
44 on the level of the abstract code, i.e. before any programming language code is
45 generated. Here are some examples of errors that are caught this way::
46
47 >>> G.v = 3*ms # G.variables['v'].unit is volt # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
48 Traceback (most recent call last):
49 ...
50 DimensionMismatchError: v should be set with a value with units volt, but got 3. ms (unit is second).
51 >>> G.N = 5 # G.variables['N'] is read-only # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
52 Traceback (most recent call last):
53 ...
54 TypeError: Variable N is read-only
55
56 Creating variables
57 ------------------
58 Each variable that should be accessible as a state variable and/or should be
59 available for use in abstract code has to be created as a `Variable`. For this,
60 first a `Variables` container with a reference to the group has to be created,
61 individual variables can then be added using the various ``add_...`` methods::
62
63 self.variables = Variables(self)
64 self.variables.add_array('an_array', unit=volt, size=100)
65 self.variables.add_constant('N', unit=Unit(1), value=self._N, dtype=np.int32)
66 self.variables.create_clock_variables(self.clock)
67
68 As an additional argument, array variables can be specified with a specific
69 *index* (see `Indices`_ below).
70
71 References
72 ----------
73 For each variable, only one `Variable` object exists even if it is used in
74 different contexts. Let's consider the following example::
75
76 >>> G = NeuronGroup(5, 'dv/dt = -v / tau : volt', threshold='v > 1', reset='v = 0',
77 ... name='neurons')
78 >>> subG = G[2:]
79 >>> S = Synapses(G, G, on_pre='v+=1*mV', name='synapses')
80 >>> S.connect()
81
82 All allow an access to the state variable `v` (note the different shapes, these
83 arise from the different indices used, see below)::
84
85 >>> G.v
86 <neurons.v: array([ 0., 0., 0., 0., 0.]) * volt>
87 >>> subG.v
88 <neurons_subgroup.v: array([ 0., 0., 0.]) * volt>
89 >>> S.v
90 <synapses.v: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
91 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) * volt>
92
93 In all of these cases, the `Variables` object stores references to the same
94 `ArrayVariable` object::
95
96 >>> id(G.variables['v']) # doctest: +SKIP
97 108610960
98 >>> id(subG.variables['v']) # doctest: +SKIP
99 108610960
100 >>> id(S.variables['v']) # doctest: +SKIP
101 108610960
102
103 Such a reference can be added using `Variables.add_reference`, note that the
104 name used for the reference is not necessarily the same as in the original
105 group, e.g. in the above example ``S.variables`` also stores references to ``v``
106 under the names ``v_pre`` and ``v_post``.
107
108 Indices
109 -------
110 In subgroups and especially in synapses, the transformation of abstract code
111 into executable code is not straightforward because it can involve variables
112 from different contexts. Here is a simple example::
113
114 >>> G = NeuronGroup(5, 'dv/dt = -v / tau : volt', threshold='v > 1', reset='v = 0')
115 >>> S = Synapses(G, G, 'w : volt', on_pre='v+=w')
116
117 The seemingly trivial operation ``v+=w`` involves the variable ``v`` of the
118 `NeuronGroup` and the variable ``w`` of the `Synapses` object which have to be
119 indexed in the appropriate way. Since this statement is executed in the context
120 of ``S``, the variable indices stored there are relevant::
121
122 >>> S.variables.indices['w']
123 '_idx'
124 >>> S.variables.indices['v']
125 '_postsynaptic_idx'
126
127 The index ``_idx`` has a special meaning and always refers to the "natural"
128 index for a group (e.g. all neurons for a `NeuronGroup`, all synapses for a
129 `Synapses` object, etc.). All other indices have to refer to existing arrays::
130
131 >>> S.variables['_postsynaptic_idx'] # doctest: +SKIP
132 <DynamicArrayVariable(dimensions=Dimension(), dtype=<class 'numpy.int32'>, scalar=False, constant=True, read_only=True)>
133
134 In this case, ``_postsynaptic_idx`` refers to a dynamic array that stores the
135 postsynaptic targets for each synapse (since it is an array itself, it also has
136 an index. It is defined for each synapse so its index is ``_idx`` -- in fact
137 there is currently no support for an additional level of indirection in Brian:
138 a variable representing an index has to have ``_idx`` as its own index). Using
139 this index information, the following C++ code (slightly simplified) is
140 generated:
141
142 .. code-block:: c++
143
144 for(int _spiking_synapse_idx=0;
145 _spiking_synapse_idx<_num_spiking_synapses;
146 _spiking_synapse_idx++)
147 {
148 const int _idx = _spiking_synapses[_spiking_synapse_idx];
149 const int _postsynaptic_idx = _ptr_array_synapses__synaptic_post[_idx];
150 const double w = _ptr_array_synapses_w[_idx];
151 double v = _ptr_array_neurongroup_v[_postsynaptic_idx];
152 v += w;
153 _ptr_array_neurongroup_v[_postsynaptic_idx] = v;
154 }
155
156 In this case, the "natural" index ``_idx`` iterates over all the synapses that
157 received a spike (this is defined in the template) and ``_postsynaptic_idx``
158 refers to the postsynaptic targets for these synapses. The variables ``w`` and
159 ``v`` are then pulled out of their respective arrays with these indices so that
160 the statement ``v += w;`` does the right thing.
161
162 Getting and setting state variables
163 -----------------------------------
164 When a state variable is accessed (e.g. using ``G.v``), the group does not
165 return a reference to the underlying array itself but instead to a
166 `VariableView` object. This is because a state variable can be accessed in
167 different contexts and indexing it with a number/array (e.g. ``obj.v[0]``) or
168 a string (e.g. ``obj.v['i>3']``) can refer to different values in the underlying
169 array depending on whether the object is the `NeuronGroup`, a `Subgroup` or
170 a `Synapses` object.
171
172 The ``__setitem__`` and ``__getitem__`` methods in `VariableView` delegate to
173 `VariableView.set_item` and `VariableView.get_item` respectively (which can also
174 be called directly under special circumstances). They analyze the arguments (is
175 the index a number, a slice or a string? Is the target value an array or a string
176 expression?) and delegate the actual retrieval/setting of the values to a
177 specific method:
178
179 * Getting with a numerical (or slice) index (e.g. ``G.v[0]``): `VariableView.get_with_index_array`
180 * Getting with a string index (e.g. ``G.v['i>3']``): `VariableView.get_with_expression`
181 * Setting with a numerical (or slice) index and a numerical target value (e.g.
182 ``G.v[5:] = -70*mV``): `VariableView.set_with_index_array`
183 * Setting with a numerical (or slice) index and a string expression value (e.g.
184 ``G.v[5:] = (-70+i)*mV``): `VariableView.set_with_expression`
185 * Setting with a string index and a string expression value (e.g.
186 ``G.v['i>5'] = (-70+i)*mV``): `VariableView.set_with_expression_conditional`
187
188 These methods are annotated with the `device_override` decorator and can
189 therefore be implemented in a different way in certain devices. The standalone
190 device, for example, overrides the all the getting functions and the setting
191 with index arrays. Note that for standalone devices, the "setter" methods do
192 not actually set the values but only note them down for later code generation.
193
194 Additional variables and indices
195 --------------------------------
196 The variables stored in the ``variables`` attribute of a `VariableOwner` can
197 be used everywhere (e.g. in the state updater, in the threshold, the reset,
198 etc.). Objects that depend on these variables, e.g. the `Thresholder` of a
199 `NeuronGroup` add additional variables, in particular `AuxiliaryVariables` that
200 are automatically added to the abstract code: a threshold condition ``v > 1``
201 is converted into the statement ``_cond = v > 1``; to specify the meaning of
202 the variable ``_cond`` for the code generation stage (in particular, C++ code
203 generation needs to know the data type) an `AuxiliaryVariable` object is created.
204
205 In some rare cases, a specific ``variable_indices`` dictionary is provided
206 that overrides the indices for variables stored in the ``variables`` attribute.
207 This is necessary for synapse creation because the meaning of the variables
208 changes in this context: an expression ``v>0`` does not refer to the ``v``
209 variable of all the *connected* postsynaptic variables, as it does under other
210 circumstances in the context of a `Synapses` object, but to the ``v`` variable
211 of all *possible* targets.