Debian Codegraph @

brian2/stateupdaters/GSL.py

raw
1 """
2 Module containg the StateUpdateMethod for integration using the ODE solver
3 provided in the GNU Scientific Library (GSL)
4 """
5
6 import os
7 import sys
8
9 from brian2.utils.logger import get_logger
10
11 from ..core.preferences import prefs
12 from ..devices.device import RuntimeDevice, all_devices, auto_target
13 from .base import (
14 StateUpdateMethod,
15 UnsupportedEquationsException,
16 extract_method_options,
17 )
18
19 logger = get_logger(__name__)
20
21 __all__ = ["gsl_rk2", "gsl_rk4", "gsl_rkf45", "gsl_rkck", "gsl_rk8pd"]
22
23 default_method_options = {
24 "adaptable_timestep": True,
25 "absolute_error": 1e-6,
26 "absolute_error_per_variable": None,
27 "max_steps": 100,
28 "use_last_timestep": True,
29 "save_failed_steps": False,
30 "save_step_count": False,
31 }
32
33
34 class GSLContainer:
35 """
36 Class that contains information (equation- or integrator-related) required
37 for later code generation
38 """
39
40 def __init__(
41 self,
42 method_options,
43 integrator,
44 abstract_code=None,
45 needed_variables=None,
46 variable_flags=None,
47 ):
48 if needed_variables is None:
49 needed_variables = []
50 if variable_flags is None:
51 variable_flags = []
52 self.method_options = method_options
53 self.integrator = integrator
54 self.abstract_code = abstract_code
55 self.needed_variables = needed_variables
56 self.variable_flags = variable_flags
57
58 def get_codeobj_class(self):
59 """
60 Return codeobject class based on target language and device.
61
62 Choose which version of the GSL `CodeObject` to use. If
63 ```isinstance(device, CPPStandaloneDevice)```, then
64 we want the `GSLCPPStandaloneCodeObject`. Otherwise the return value is
65 based on prefs.codegen.target.
66
67 Returns
68 -------
69 code_object : class
70 The respective `CodeObject` class (i.e. either
71 `GSLCythonCodeObject` or `GSLCPPStandaloneCodeObject`).
72 """
73 # imports in this function to avoid circular imports
74 from brian2.devices.cpp_standalone.device import CPPStandaloneDevice
75 from brian2.devices.device import get_device
76
77 from ..codegen.runtime.GSLcython_rt import GSLCythonCodeObject
78
79 device = get_device()
80 if (
81 device.__class__ is CPPStandaloneDevice
82 ): # We do not want to accept subclasses here
83 from ..devices.cpp_standalone.GSLcodeobject import (
84 GSLCPPStandaloneCodeObject,
85 )
86
87 # In runtime mode (i.e. Cython), the compiler settings are
88 # added for each `CodeObject` (only the files that use the GSL are
89 # linked to the GSL). However, in C++ standalone mode, there are global
90 # compiler settings that are used for all files (stored in the
91 # `CPPStandaloneDevice`). Furthermore, header file includes are directly
92 # inserted into the template instead of added during the compilation
93 # phase. Therefore, we have to add the options here
94 # instead of in `GSLCPPStandaloneCodeObject`
95 # Add the GSL library if it has not yet been added
96 if "gsl" not in device.libraries:
97 device.libraries += ["gsl", "gslcblas"]
98 device.headers += [
99 "<stdio.h>",
100 "<stdlib.h>",
101 "<gsl/gsl_odeiv2.h>",
102 "<gsl/gsl_errno.h>",
103 "<gsl/gsl_matrix.h>",
104 ]
105 if sys.platform == "win32":
106 device.define_macros += [("WIN32", "1"), ("GSL_DLL", "1")]
107 if prefs.GSL.directory is not None:
108 device.include_dirs += [prefs.GSL.directory]
109 device.library_dirs += [
110 os.path.abspath(os.path.join(prefs.GSL.directory, "..", "lib"))
111 ]
112 if os.name == "nt":
113 # Add DLL directory to path
114 old_path = os.environ.get("PATH", "")
115 device.run_environment_variables["PATH"] = (
116 os.path.abspath(
117 os.path.join(prefs.GSL.directory, "..", "bin")
118 )
119 + ";"
120 + old_path
121 )
122 return GSLCPPStandaloneCodeObject
123
124 elif isinstance(device, RuntimeDevice):
125 if prefs.codegen.target == "auto":
126 target_name = auto_target().class_name
127 else:
128 target_name = prefs.codegen.target
129
130 if target_name == "cython":
131 return GSLCythonCodeObject
132 raise NotImplementedError(
133 "GSL integration has not been implemented for "
134 f"for the '{target_name}' code generation target."
135 "\nUse the 'cython' code generation target, "
136 "or switch to the 'cpp_standalone' device."
137 )
138 else:
139 device_name = [name for name, dev in all_devices.items() if dev is device]
140 assert len(device_name) == 1
141 raise NotImplementedError(
142 "GSL integration has not been implemented for "
143 f"for the '{device_name[0]}' device."
144 "\nUse either the 'cpp_standalone' device, "
145 "or the runtime device with target language "
146 "'cython'."
147 )
148
149 def __call__(self, obj):
150 """
151 Transfer the code object class saved in self to the object sent as an argument.
152
153 This method is returned when calling `GSLStateUpdater`. This class inherits
154 from `StateUpdateMethod` which orignally only returns abstract code.
155 However, with GSL this returns a method because more is needed than just
156 the abstract code: the state updater requires its own CodeObject that is
157 different from the other `NeuronGroup` objects. This method adds this
158 `CodeObject` to the `StateUpdater` object (and also adds the variables
159 't', 'dt', and other variables that are needed in the `GSLCodeGenerator`.
160
161 Parameters
162 ----------
163 obj : `GSLStateUpdater`
164 the object that the codeobj_class and other variables need to be transferred to
165
166 Returns
167 -------
168 abstract_code : str
169 The abstract code (translated equations), that is returned conventionally
170 by brian and used for later code generation in the `CodeGenerator.translate` method.
171 """
172 obj.codeobj_class = self.get_codeobj_class()
173 obj._gsl_variable_flags = self.variable_flags
174 obj.method_options = self.method_options
175 obj.integrator = self.integrator
176 obj.needed_variables = ["t", "dt"] + self.needed_variables
177 return self.abstract_code
178
179
180 class GSLStateUpdater(StateUpdateMethod):
181 """
182 A statupdater that rewrites the differential equations so that the GSL generator
183 knows how to write the code in the target language.
184
185 .. versionadded:: 2.1
186 """
187
188 def __init__(self, integrator):
189 self.integrator = integrator
190
191 def __call__(self, equations, variables=None, method_options=None):
192 """
193 Translate equations to abstract_code.
194
195 Parameters
196 ----------
197 equations : `Equations`
198 object containing the equations that describe the ODE systemTransferClass(self)
199 variables : dict
200 dictionary containing str, `Variable` pairs
201
202 Returns
203 -------
204 method : callable
205 Method that needs to be called with `StateUpdater` to add CodeObject
206 class and some other variables so these can be sent to the `CodeGenerator`
207 """
208 logger.warn(
209 "Integrating equations with GSL is still considered experimental", once=True
210 )
211
212 method_options = extract_method_options(method_options, default_method_options)
213
214 if equations.is_stochastic:
215 raise UnsupportedEquationsException(
216 "Cannot solve stochastic equations with the GSL state updater."
217 )
218
219 # the approach is to 'tag' the differential equation variables so they can
220 # be translated to GSL code
221 diff_eqs = equations.get_substituted_expressions(variables)
222
223 code = []
224 count_statevariables = 0
225 counter = {}
226 diff_vars = []
227
228 for diff_name, expr in diff_eqs:
229 # if diff_name does not occur in the right hand side of the equation, Brian does not
230 # know to add the variable to the namespace, so we add it to needed_variables
231 diff_vars += [diff_name]
232 counter[diff_name] = count_statevariables
233 code += [f"_gsl_{diff_name}_f{counter[diff_name]} = {expr}"]
234 count_statevariables += 1
235
236 # add flags to variables objects because some of them we need in the GSL generator
237 flags = {}
238 for eq_name, eq_obj in equations._equations.items():
239 if len(eq_obj.flags) > 0:
240 flags[eq_name] = eq_obj.flags
241
242 return GSLContainer(
243 method_options=method_options,
244 integrator=self.integrator,
245 abstract_code=("\n").join(code),
246 needed_variables=diff_vars,
247 variable_flags=flags,
248 )
249
250
251 gsl_rk2 = GSLStateUpdater("rk2")
252 gsl_rk4 = GSLStateUpdater("rk4")
253 gsl_rkf45 = GSLStateUpdater("rkf45")
254 gsl_rkck = GSLStateUpdater("rkck")
255 gsl_rk8pd = GSLStateUpdater("rk8pd")