Debian Codegraph @

brian2/codegen/runtime/cython_rt/cython_rt.py

raw
1 import platform
2
3 import numpy
4
5 from brian2.core.base import BrianObjectException
6 from brian2.core.functions import Function
7 from brian2.core.preferences import BrianPreference, prefs
8 from brian2.core.variables import (
9 ArrayVariable,
10 AuxiliaryVariable,
11 DynamicArrayVariable,
12 Subexpression,
13 )
14 from brian2.utils.logger import get_logger
15 from brian2.utils.stringtools import get_identifiers
16
17 from ...codeobject import check_compiler_kwds, constant_or_scalar
18 from ...cpp_prefs import get_compiler_and_args
19 from ...generators.cython_generator import (
20 CythonCodeGenerator,
21 get_cpp_dtype,
22 get_numpy_dtype,
23 )
24 from ...targets import codegen_targets
25 from ...templates import Templater
26 from ..numpy_rt import NumpyCodeObject
27 from .extension_manager import cython_extension_manager
28
29 __all__ = ["CythonCodeObject"]
30
31
32 logger = get_logger(__name__)
33
34 # Preferences
35 prefs.register_preferences(
36 "codegen.runtime.cython",
37 "Cython runtime codegen preferences",
38 multiprocess_safe=BrianPreference(
39 default=True,
40 docs="""
41 Whether to use a lock file to prevent simultaneous write access
42 to cython .pyx and .so files.
43 """,
44 ),
45 cache_dir=BrianPreference(
46 default=None,
47 validator=lambda x: x is None or isinstance(x, str),
48 docs="""
49 Location of the cache directory for Cython files. By default,
50 will be stored in a ``brian_extensions`` subdirectory
51 where Cython inline stores its temporary files
52 (the result of ``get_cython_cache_dir()``).
53 """,
54 ),
55 delete_source_files=BrianPreference(
56 default=True,
57 docs="""
58 Whether to delete source files after compiling. The Cython
59 source files can take a significant amount of disk space, and
60 are not used anymore when the compiled library file exists.
61 They are therefore deleted by default, but keeping them around
62 can be useful for debugging.
63 """,
64 ),
65 )
66
67
68 class CythonCodeObject(NumpyCodeObject):
69 """
70 Execute code using Cython.
71 """
72
73 templater = Templater(
74 "brian2.codegen.runtime.cython_rt",
75 ".pyx",
76 env_globals={
77 "cpp_dtype": get_cpp_dtype,
78 "numpy_dtype": get_numpy_dtype,
79 "dtype": numpy.dtype,
80 "constant_or_scalar": constant_or_scalar,
81 },
82 )
83 generator_class = CythonCodeGenerator
84 class_name = "cython"
85
86 def __init__(
87 self,
88 owner,
89 code,
90 variables,
91 variable_indices,
92 template_name,
93 template_source,
94 compiler_kwds,
95 name="cython_code_object*",
96 ):
97 check_compiler_kwds(
98 compiler_kwds,
99 [
100 "libraries",
101 "include_dirs",
102 "library_dirs",
103 "runtime_library_dirs",
104 "sources",
105 ],
106 "Cython",
107 )
108 super().__init__(
109 owner,
110 code,
111 variables,
112 variable_indices,
113 template_name,
114 template_source,
115 compiler_kwds={}, # do not pass the actual args
116 name=name,
117 )
118 self.compiler, self.extra_compile_args = get_compiler_and_args()
119 self.define_macros = list(prefs["codegen.cpp.define_macros"])
120 self.extra_link_args = list(prefs["codegen.cpp.extra_link_args"])
121 self.headers = [] # not actually used
122
123 self.include_dirs = list(prefs["codegen.cpp.include_dirs"]) + compiler_kwds.get(
124 "include_dirs", []
125 )
126 self.include_dirs = list(prefs["codegen.cpp.include_dirs"])
127
128 self.library_dirs = list(prefs["codegen.cpp.library_dirs"]) + compiler_kwds.get(
129 "library_dirs", []
130 )
131
132 self.runtime_library_dirs = list(
133 prefs["codegen.cpp.runtime_library_dirs"]
134 ) + compiler_kwds.get("runtime_library_dirs", [])
135
136 self.libraries = list(prefs["codegen.cpp.libraries"]) + compiler_kwds.get(
137 "libraries", []
138 )
139 self.sources = compiler_kwds.get("sources", [])
140
141 @classmethod
142 def is_available(cls):
143 try:
144 compiler, extra_compile_args = get_compiler_and_args()
145 code = """
146 #cython: language_level=3
147 def main():
148 cdef int x
149 x = 0"""
150 compiled = cython_extension_manager.create_extension(
151 code,
152 compiler=compiler,
153 extra_compile_args=extra_compile_args,
154 extra_link_args=prefs["codegen.cpp.extra_link_args"],
155 include_dirs=prefs["codegen.cpp.include_dirs"],
156 library_dirs=prefs["codegen.cpp.library_dirs"],
157 runtime_library_dirs=prefs["codegen.cpp.runtime_library_dirs"],
158 )
159 compiled.main()
160 return True
161 except Exception as ex:
162 msg = (
163 f"Cannot use Cython, a test compilation failed: {str(ex)} "
164 f"({ex.__class__.__name__})"
165 )
166 if platform.system() != "Windows":
167 msg += (
168 "\nCertain compiler configurations (e.g. clang in a conda "
169 "environment on OS X) are known to be problematic. Note that "
170 "you can switch the compiler by setting the 'CC' and 'CXX' "
171 "environment variables. For example, you may want to try "
172 "'CC=gcc' and 'CXX=g++'."
173 )
174 logger.warn(msg, "failed_compile_test")
175 return False
176
177 def compile_block(self, block):
178 code = getattr(self.code, block, "").strip()
179 if not code or "EMPTY_CODE_BLOCK" in code:
180 return None
181 return cython_extension_manager.create_extension(
182 code,
183 define_macros=self.define_macros,
184 libraries=self.libraries,
185 extra_compile_args=self.extra_compile_args,
186 extra_link_args=self.extra_link_args,
187 include_dirs=self.include_dirs,
188 library_dirs=self.library_dirs,
189 runtime_library_dirs=self.runtime_library_dirs,
190 compiler=self.compiler,
191 owner_name=f"{self.owner.name}_{self.template_name}",
192 sources=self.sources,
193 )
194
195 def run_block(self, block):
196 compiled_code = self.compiled_code[block]
197 if compiled_code:
198 try:
199 return compiled_code.main(self.namespace)
200 except Exception as exc:
201 message = (
202 "An exception occured during the execution of the "
203 f"'{block}' block of code object '{self.name}'.\n"
204 )
205 raise BrianObjectException(message, self.owner) from exc
206
207 def _insert_func_namespace(self, func):
208 impl = func.implementations[self]
209 func_namespace = impl.get_namespace(self.owner)
210 if func_namespace is not None:
211 self.namespace.update(func_namespace)
212 if impl.dependencies is not None:
213 for dep in impl.dependencies.values():
214 self._insert_func_namespace(dep)
215
216 def variables_to_namespace(self):
217 # Variables can refer to values that are either constant (e.g. dt)
218 # or change every timestep (e.g. t). We add the values of the
219 # constant variables here and add the names of non-constant variables
220 # to a list
221
222 # A list containing tuples of name and a function giving the value
223 self.nonconstant_values = []
224
225 for name, var in self.variables.items():
226 if isinstance(var, Function):
227 self._insert_func_namespace(var)
228 if isinstance(var, (AuxiliaryVariable, Subexpression)):
229 continue
230 try:
231 value = var.get_value()
232 except (TypeError, AttributeError):
233 # A dummy Variable without value or a function
234 self.namespace[name] = var
235 continue
236
237 if isinstance(var, ArrayVariable):
238 self.namespace[self.device.get_array_name(var, self.variables)] = value
239 self.namespace[f"_num{name}"] = var.get_len()
240 if var.scalar and var.constant:
241 self.namespace[name] = value.item()
242 else:
243 self.namespace[name] = value
244
245 if isinstance(var, DynamicArrayVariable):
246 dyn_array_name = self.generator_class.get_array_name(
247 var, access_data=False
248 )
249 # Adding logic to pass in the capsule object to namespace , we already have code set in generator to
250 # take the passed in object and work on it
251 capsule_name = f"{dyn_array_name}_capsule"
252 capsule = self.device.get_capsule(var)
253 self.namespace[capsule_name] = capsule
254 self.namespace[dyn_array_name] = self.device.get_value(
255 var, access_data=False
256 )
257
258 # Also provide the Variable object itself in the namespace (can be
259 # necessary for resize operations, for example)
260 self.namespace[f"_var_{name}"] = var
261
262 # Get all identifiers in the code -- note that this is not a smart
263 # function, it will get identifiers from strings, comments, etc. This
264 # is not a problem here, since we only use this list to filter out
265 # things. If we include something incorrectly, this only means that we
266 # will pass something into the namespace unnecessarily.
267 all_identifiers = get_identifiers(self.code.run)
268 # Filter out all unneeded objects
269 self.namespace = {
270 k: v for k, v in self.namespace.items() if k in all_identifiers
271 }
272 # There is one type of objects that we have to inject into the
273 # namespace with their current value at each time step: dynamic
274 # arrays that change in size during runs, where the size change is not
275 # initiated by the template itself
276 for name, var in self.variables.items():
277 if isinstance(var, DynamicArrayVariable) and var.needs_reference_update:
278 array_name = self.device.get_array_name(var, self.variables)
279 if array_name in self.namespace:
280 self.nonconstant_values.append((array_name, var.get_value))
281 if f"_num{name}" in self.namespace:
282 self.nonconstant_values.append((f"_num{name}", var.get_len))
283
284 def update_namespace(self):
285 # update the values of the non-constant values in the namespace
286 for name, func in self.nonconstant_values:
287 self.namespace[name] = func()
288
289
290 codegen_targets.add(CythonCodeObject)