Debian Codegraph @

docs_sphinx/developer/GSL.rst

raw
1 Solving differential equations with the GNU Scientific Library
2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3
4 Conventionally, Brian generates its own code performing :doc:`../user/numerical_integration`
5 according to the chosen algorithm (see the section on :doc:`codegen`).
6 Another option is to let the differential equation solvers defined in the
7 `GNU Scientific Library (GSL) <https://www.gnu.org/software/gsl/doc/html/ode-initval.html>`_
8 solve the given equations. In addition to offering a few extra integration methods,
9 the GSL integrator comes with the option of having an adaptable timestep. The
10 latter functionality can have benefits for the speed with which large simulations
11 can be run. This is because it allows the use of larger timesteps for the overhead
12 loops in Python, without losing the accuracy of the numerical integration at points
13 where small timesteps are necessary. In addition, a major benefit of using the ODE
14 solvers from GSL is that an estimation is performed on how wrong the current solution
15 is, so that simulations can be performed with some confidence on accuracy.
16 (Note however that the confidence of accuracy is based on estimation!)
17
18 StateUpdateMethod
19 -----------------
20
21 Translation of equations to abstract code
22 +++++++++++++++++++++++++++++++++++++++++
23
24 The first part of Brian's code generation is the translation of equations to what we
25 call 'abstract code'. In the case of Brian's stateupdaters so far, this abstract
26 code describes the calculations that need to be done to update differential variables
27 depending on their equations as is explained in the section on :doc:`../advanced/state_update`.
28 In the case of preparing the equations for GSL integration this is a bit different.
29 Instead of writing down the computations that have to be done to reach the new value
30 of the variable after a time step, the equations have to be described in a way that
31 GSL understands. The differential equations have to be defined in a function and
32 the function is given to GSL. This is best explained with an example. If we have
33 the following equations (taken from the adaptive threshold example):
34
35 .. code-block:: none
36
37 dv/dt = -v/(10*ms) : volt
38 dvt/dt = (10*mV - vt)/(15*ms) : volt
39
40 We would describe the equations to GSL as follows:
41
42 .. code-block:: C
43
44 v = y[0]
45 vt = y[1]
46 f[0] = -v/(10e-3)
47 f[1] = (10e-3 - vt)
48
49 Each differential variable gets an index. Its value at any time is saved in the
50 ``y``-array and the derivatives are saved in the ``f``-array.
51 However, doing this translation in the stateupdater would mean that Brian has to
52 deal with variable descriptions that contain array accessing: something that for
53 example sympy doesn't do. Because we still want to use Brian's existing parsing
54 and checking mechanisms, we needed to find a way to describe the abstract code with
55 only 'normal' variable names.
56 Our solution is to replace the ``y[0]``, ``f[0]``, etc. with a 'normal' variable name
57 that is later replaced just before the final code generation (in the `GSLCodeGenerator`).
58 It has a tag and all the information needed to write the final code. As an example,
59 the GSL abstract code for the above equations would be:
60
61 .. code-block:: C
62
63 v = _gsl_y0
64 vt = _gsl_y1
65 _gsl_f0 = -v/(10e-3)
66 _gsl_f1 = (10e-3 - vt)
67
68 In the `GSLCodeGenerator` these tags get replaced by the actual accessing of the arrays.
69
70 Return value of the StateUpdateMethod
71 +++++++++++++++++++++++++++++++++++++
72
73 So far, for each each code generation language (numpy, cython) there was just
74 one set of rules of how to translate abstract code to real code, described in
75 its respective `CodeObject` and `CodeGenerator`. If the target language is set
76 to Cython, the stateupdater will use the `CythonCodeObject`, just like other
77 objects such as the `StateMonitor`. However, to achieve the above decribed
78 translations of the abstract code generated by the `StateUpdateMethod`, we
79 need a special `CythonCodeObject` for the stateupdater alone (which at its turn
80 can contain the special `CodeGenerator`), and this `CodeObject` should be
81 selected based on the chosen `StateUpdateMethod`.
82
83 In order to achieve `CodeObject` selection based on the chosen stateupdater, the
84 `StateUpdateMethod` returns a class that can be called with an object, and the
85 appropriate `CodeObject` is added as an attribute to the given object. The return
86 value of this callable is the abstract code describing the equations in a
87 language that makes sense to the `GSLCodeGenerator`.
88
89 GSLCodeObject
90 -------------
91 Each target language has its own `GSLCodeObject` that is derived from the
92 already existing code object of its language. There are only minimal changes
93 to the already existing code object:
94
95 * Overwrite ``stateupate`` template: a new version of the ``stateupdate``
96 template is given (``stateupdate.cpp`` for C++ standalone and
97 ``stateupdate.pyx`` for cython).
98 * Have a GSL specific generator_class: `GSLCythonCodeGenerator`
99 * Add the attribute ``original_generator_class``: the conventional
100 target-language generator is used to do the bulk of the translation to get
101 from abstract code to language-specific code.
102
103 This defining of GSL-specific code objects also allowed us to catch compilation
104 errors so we can give the user some information on that it might be GSL-related
105 (overwriting the ``compile()`` method in the case of cython). In the case of
106 the C++ `CodeObject` such overriding wasn't really possible so compilation
107 errors in this case might be quite undescriptive.
108
109 GSLCodeGenerator
110 ----------------
111 This is where the magic happens. Roughly 1000 lines of code define the
112 translation of abstract code to code that uses the GNU Scientific Library's ODE
113 solvers to achieve state updates.
114
115 Upon a call to `run`, the code objects necessary for the simulation get made.
116 The code for this is described in the device. Part of making the code objects
117 is generating the code that describes the code objects. This starts with a
118 call to ``translate``, which in the case of GSL brings us to
119 the `GSLCodeGenerator.translate()`. This method is built up as follows:
120
121 * Some GSL-specific preparatory work:
122
123 - Check whether the equations contain variable names that are reserved for
124 the GSL code.
125 - Add the 'gsl tags' (see section on StateUpdateMethod) to the
126 variables known to Brian as non-scalars. This is necessary to ensure that
127 all equations containing 'gsl tags' are considered vector equations, and
128 thus added to Brian's vector code.
129 - Add GSL integrator meta variables as official Brian variables, so these
130 are also taken into account upon translation. The meta variables that are
131 possible are described in the user manual (e.g. GSL's step taken in a
132 single overhead step '_step_count').
133 - Save function names. The original generators delete the function names
134 from the variables dictionary once they are processed. However, we need to
135 know later in the GSL part of the code generation whether a certain encountered
136 variable name refers to a function or not.
137
138 * Brian's general preparatory work. This piece of code is directly copied from
139 the base CodeGenerator and is thus similar to what is done normally.
140 * A call to ``original_generator.translate()`` to get the abstract code translated
141 into code that is target-language specific.
142 * A lot of statements to translate the target-language specific code to
143 GSL-target-language specific code, described in more detail below.
144
145 The biggest difference between conventional Brian code and GSL code is that
146 the stateupdate-decribing lines are contained directly in the ``main()`` or in a
147 separate function, respectively. In both cases, the equations describing the
148 system refer to parameters that are in the Brian namespace (e.g. "dv/dt =
149 -v/tau" needs access to "tau"). How can we access Brian's namespace in this
150 separate function that is needed with GSL?
151
152 To explain the solution we first need some background information on this
153 'separate function' that is given to the GSL integrators: ``_GSL_func``.
154 This function always gets three arguments:
155
156 * ``double t``: the current time. This is relevant when the equations are
157 dependent on time.
158 * ``const double _GSL_y[]``': an array containing the current values of the
159 differential variables (const because the cannot be changed by _GSL_func
160 itself).
161 * ``double f[]``: an array containing the derivatives of the differential
162 variables (i.e. the equations describing the differential system).
163 * ``void * params``: a pointer.
164
165 The pointer can be a pointer to whatever you want, and can thus point to a
166 data structure containing the system parameters (such as tau). To achieve
167 a structure containing all the parameters of the system, a considerable
168 amount of code has to be added/changed to that generated by conventional Brian:
169
170 * The data structure, _GSL_dataholder, has to be defined with all variables
171 needed in the vector code. For this reason, also the datatype of each variable is required.
172
173 - This is done in the method `GSLCodeGenerator.write_dataholder`
174
175 * Instead of referring to the variables by their name only (e.g. ``dv/dt =
176 -v/tau``), the variables have to be accessed as part of the data structure
177 (e.g. ``dv/dt = -v/_GSL_dataholder->tau`` in the case of cpp). Also, as
178 mentioned earlier, we want to translate the 'gsl tags' to what they should be
179 in the final code (e.g. ``_gsl_f0`` to ``f[0]``).
180
181 - This is done in the method `GSLCodeGenerator.translate_vector_code`. It works
182 based on the
183 to_replace dictionary (generated in the methods
184 `GSLCodeGenerator.diff_var_to_replace` and
185 `GSLCodeGenerator.to_replace_vector_vars`) that
186 simply contains the old variables as keys and
187 new variables as values, and is given to the word_replace function.
188
189 * The values of the variables in the data structure have to be set to the
190 values of the variables in the Brian namespace.
191
192 - This is done in the method `GSLCodeGenerator.unpack_namespace`, and for the
193 'scalar' variables that require calculation first it is done in the method
194 `GSLCodeGenerator.translate_scalar_code`.
195
196 In addition, a few more 'support' functions are generated for the GSL script:
197
198
199 * ``int _set_dimension(size_t * dimension)``: sets the dimension of the system.
200 Required for GSL.
201 * ``double* _assign_memory_y()``: allocates the right amount of memory for the y
202 array (also according to the dimension of the system).
203 * ``int _fill_y_vector(_dataholder* _GSL_dataholder, double* _GSL_y, int _idx)``:
204 pulls out the values for each differential variable out of the 'Brian' array
205 into the y-vector. This happens in the vector loop
206 (e.g. ``y[0] = _GSL_dataholder->_ptr_array_neurongroup_v[_idx];`` for C++).
207 * ``int _empty_y_vector(_dataholder* _GSL_dataholder, double* _GSL_y, int _idx)``:
208 the opposite of _fill_y_vector. Pulls final numerical solutions from the y array
209 and gives it back to Brian's namespace.
210 * ``double* _set_GSL_scale_array()``: sets the array bound for each differential
211 variable, for which the values are based on ``method_options['absolute_error']`` and
212 ``method_options['absolute_error_per_variable']``.
213
214 All of this is written in support functions so that the vector code in the ``main()``
215 can stay almost constant for any simulation.
216
217 Stateupdate templates
218 ---------------------
219
220 There is many extra things that need to be done for each simulation when using GSL
221 compared to conventional Brian stateupdaters. These are summarized in this section.
222
223 Things that need to be done for every type of simulation (either before, in or after ``main()``):
224
225 * Cython-only: define the structs and functions that we will be using in cython language.
226 * Prepare the ``gsl_odeiv2_system``: give function pointer, set dimension, give pointer to ``_GSL_dataholder`` as params.
227 * Allocate the driver (name for the struct that contains the info necessary to perform GSL integration)
228 * Define dt.
229
230 Things that need to be done every loop iteration for every type of simulation:
231
232 * Define t and t1 (t + dt).
233 * Transfer the values in the Brian arrays to the y-array that will be given to GSL.
234 * Set ``_GSL_dataholder._idx`` (in case we need to access array variables in ``_GSL_func``).
235 * Initialize the driver (reset counters, set ``dt_start``).
236 * Apply driver (either with adaptable- or fixed time step).
237 * Optionally save certain meta-variables
238 * Transfer values from GSL's y-vector to Brian arrays