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