Debian Codegraph @

docs_sphinx/developer/oldcodegen.rst

raw
1 Older notes on code generation
2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3
4 The following is an outline of how the Brian 2 code generation system works,
5 with indicators as to which packages to look at and which bits of code to read
6 for a clearer understanding.
7
8 We illustrate the global process with an example, the creation and running of
9 a single `NeuronGroup` object:
10
11 - Parse the equations, add refractoriness to them: this isn't really part of
12 code generation.
13
14 - Allocate memory for the state variables.
15
16 - Create `Thresholder`, `Resetter` and `StateUpdater` objects.
17
18 - Determine all the variable and function names used in the respective
19 abstract code blocks and templates
20
21 - Determine the abstract namespace, i.e. determine a `Variable` or `Function`
22 object for each name.
23
24 - Create a `CodeObject` based on the abstract code, template and abstract
25 namespace. This will generate code in the target language and the namespace
26 in which the code will be executed.
27
28 - At runtime, each object calls `CodeObject.__call__` to execute the code.
29
30 Stages of code generation
31 =========================
32
33 Equations to abstract code
34 --------------------------
35
36 In the case of `Equations`, the set of equations are combined with a
37 numerical integration method to generate an *abstract code block* (see below)
38 which represents the integration code for a single time step.
39
40 An example of this would be converting the following equations::
41
42 eqs = '''
43 dv/dt = (v0-v)/tau : volt (unless refractory)
44 v0 : volt
45 '''
46 group = NeuronGroup(N, eqs, threshold='v>10*mV',
47 reset='v=0*mV', refractory=5*ms)
48
49 into the following abstract code using the `exponential_euler` method (which
50 is selected automatically)::
51
52 not_refractory = 1*((t - lastspike) > 0.005000)
53 _BA_v = -v0
54 _v = -_BA_v + (_BA_v + v)*exp(-dt*not_refractory/tau)
55 v = _v
56
57 The code for this stage can be seen in `NeuronGroup.__init__`,
58 `StateUpdater.__init__`, and `StateUpdater.update_abstract_code`
59 (in ``brian2.groups.neurongroup``), and the `StateUpdateMethod` classes
60 defined in the ``brian2.stateupdaters`` package.
61
62 For more details, see :doc:`../advanced/state_update`.
63
64 Abstract code
65 -------------
66
67 'Abstract code' is just a multi-line string representing a block of code which
68 should be executed for each item (e.g. each neuron, each synapse). Each item
69 is independent of the others in abstract code. This allows us to later
70 generate code either for vectorised languages (like numpy in Python) or
71 using loops (e.g. in C++).
72
73 Abstract code is parsed according to Python syntax, with certain language
74 constructs excluded. For example, there cannot be any conditional or looping
75 statements at the moment, although support for this is in principle possible
76 and may be added later. Essentially, all that is allowed at the moment is a
77 sequence of arithmetical ``a = b*c`` style statements.
78
79 Abstract code is provided directly by the user for threshold and reset
80 statements in `NeuronGroup` and for pre/post spiking events in `Synapses`.
81
82 Abstract code to snippet
83 ------------------------
84
85 We convert abstract code into a 'snippet', which is a small segment of
86 code which is syntactically correct in the target language, although it may
87 not be runnable on its own (that's handled by insertion into a 'template'
88 later). This is handled by the `CodeGenerator` object in ``brian2.codegen.generators``.
89 In the case of converting into python/numpy code this typically doesn't involve
90 any changes to the code at all because the original code is in Python
91 syntax. For conversion to C++, we have to do some syntactic transformations
92 (e.g. ``a**b`` is converted to ``pow(a, b)``), and add declarations for
93 certain variables (e.g. converting ``x=y*z`` into ``const double x = y*z;``).
94
95 An example of a snippet in C++ for the equations above::
96
97 const double v0 = _ptr_array_neurongroup_v0[_neuron_idx];
98 const double lastspike = _ptr_array_neurongroup_lastspike[_neuron_idx];
99 bool not_refractory = _ptr_array_neurongroup_not_refractory[_neuron_idx];
100 double v = _ptr_array_neurongroup_v[_neuron_idx];
101 not_refractory = 1 * (t - lastspike > 0.0050000000000000001);
102 const double _BA_v = -(v0);
103 const double _v = -(_BA_v) + (_BA_v + v) * exp(-(dt) * not_refractory / tau);
104 v = _v;
105 _ptr_array_neurongroup_not_refractory[_neuron_idx] = not_refractory;
106 _ptr_array_neurongroup_v[_neuron_idx] = v;
107
108 The code path that includes snippet generation will be discussed in more detail
109 below, since it involves the concepts of namespaces and variables which we
110 haven't covered yet.
111
112 Snippet to code block
113 ---------------------
114
115 The final stage in the generation of a runnable code block is the insertion
116 of a snippet into a template. These use the Jinja2 template specification
117 language. This is handled in ``brian2.codegen.templates``.
118
119 An example of a template for Python thresholding::
120
121 # USES_VARIABLES { not_refractory, lastspike, t }
122 {% for line in code_lines %}
123 {{line}}
124 {% endfor %}
125 _return_values, = _cond.nonzero()
126 # Set the neuron to refractory
127 not_refractory[_return_values] = False
128 lastspike[_return_values] = t
129
130 and the output code from the example equations above::
131
132 # USES_VARIABLES { not_refractory, lastspike, t }
133 v = _array_neurongroup_v
134 _cond = v > 10 * mV
135 _return_values, = _cond.nonzero()
136 # Set the neuron to refractory
137 not_refractory[_return_values] = False
138 lastspike[_return_values] = t
139
140 Code block to executing code
141 ----------------------------
142
143 A code block represents runnable code. Brian operates in two different regimes,
144 either in runtime or standalone mode. In runtime mode, memory allocation and
145 overall simulation control is handled by Python and numpy, and code objects
146 operate on this memory when called directly by Brian. This is the typical
147 way that Brian is used, and it allows for a rapid development cycle. However,
148 we also support a standalone mode in which an entire project workspace is
149 generated for a target language or device by Brian, which can then be
150 compiled and run independently of Brian. Each mode has different templates,
151 and does different things with the outputted code blocks. For runtime mode,
152 in Python/numpy code is executed by simply calling the ``exec`` statement
153 on the code block in a given namespace. In standalone mode, the templates
154 will typically each be saved into different files.
155
156 Key concepts
157 ============
158
159 Namespaces
160 ----------
161
162 In general, a namespace is simply a mapping/dict from names to values. In Brian
163 we use the term 'namespace' in two ways: the high level "abstract namespace"
164 maps names to objects based on the `Variables` or `Function` class. In the above
165 example, ``v`` maps to an `ArrayVariable` object, ``tau`` to a `Constant`
166 object, etc. This namespace has all the information that is needed for checking
167 the consistency of units, to determine which variables are boolean or scalar,
168 etc. During the `CodeObject` creation, this abstract namespace is converted into
169 the final namespace in which the code will be executed. In this namespace, ``v``
170 maps to the numpy array storing the state variable values (without units) and
171 ``tau`` maps to a concrete value (again, without units).
172 See :doc:`equations_namespaces` for more details.
173
174 Variable
175 ----------
176
177 `Variable` objects contain information about the variable
178 they correspond to, including details like the data type, whether it is a single value
179 or an array, etc.
180
181 See ``brian2.core.variables`` and, e.g. `Group._create_variables`,
182 `NeuronGroup._create_variables`.
183
184 Templates
185 ---------
186
187 Templates are stored in Jinja2 format. They come in one of two forms, either they are a single
188 template if code generation only needs to output a single block of code, or they define multiple
189 Jinja macros, each of which is a separate code block. The `CodeObject` should define what type of
190 template it wants, and the names of the macros to define. For examples, see the templates in the
191 directories in ``brian2/codegen/runtime``. See ``brian2.codegen.templates`` for more details.
192
193 Code guide
194 ==========
195
196 This section includes a guide to the various relevant packages and subpackages
197 involved in the code generation process.
198
199 ``codegen``
200 Stores the majority of all code generation related code.
201
202 ``codegen.functions``
203 Code related to including functions - built-in and user-defined - in generated code.
204 ``codegen.generators``
205 Each `CodeGenerator` is defined in a module here.
206 ``codegen.runtime``
207 Each runtime `CodeObject` and its templates are defined in a package here.
208 ``core``
209 ``core.variables``
210 The `Variable` types are defined here.
211 ``equations``
212 Everything related to `Equations`.
213 ``groups``
214 All `Group` related stuff is in here. The `Group.resolve` methods are
215 responsible for determining the abstract namespace.
216 ``parsing``
217 Various tools using Python's ``ast`` module to parse user-specified code. Includes syntax
218 translation to various languages in ``parsing.rendering``.
219 ``stateupdaters``
220 Everything related to generating abstract code blocks from integration methods is here.