| 1 |
""" |
| 2 |
Cython automatic extension builder/manager |
| 3 |
|
| 4 |
Inspired by IPython's Cython cell magics, see: |
| 5 |
https://github.com/ipython/ipython/blob/master/IPython/extensions/cythonmagic.py |
| 6 |
""" |
| 7 |
|
| 8 |
import glob |
| 9 |
import hashlib |
| 10 |
import importlib.util |
| 11 |
import os |
| 12 |
import shutil |
| 13 |
import sys |
| 14 |
import time |
| 15 |
|
| 16 |
import numpy |
| 17 |
from distutils.command.build_ext import build_ext |
| 18 |
from distutils.core import Distribution, Extension |
| 19 |
|
| 20 |
try: |
| 21 |
import Cython |
| 22 |
import Cython.Build as Cython_Build |
| 23 |
import Cython.Compiler as Cython_Compiler |
| 24 |
|
| 25 |
try: |
| 26 |
from Cython.Utils import get_cython_cache_dir as base_cython_cache_dir |
| 27 |
except ImportError: |
| 28 |
from Cython.Build.Cache import ( |
| 29 |
get_cython_cache_dir as base_cython_cache_dir, # Cython 3.1, see cython/cython#6090 |
| 30 |
) |
| 31 |
except ImportError: |
| 32 |
Cython = None |
| 33 |
|
| 34 |
from brian2.core.preferences import prefs |
| 35 |
from brian2.utils.filelock import FileLock |
| 36 |
from brian2.utils.logger import get_logger, std_silent |
| 37 |
from brian2.utils.stringtools import deindent |
| 38 |
|
| 39 |
__all__ = ["cython_extension_manager"] |
| 40 |
|
| 41 |
logger = get_logger(__name__) |
| 42 |
|
| 43 |
|
| 44 |
def get_cython_cache_dir(): |
| 45 |
cache_dir = prefs.codegen.runtime.cython.cache_dir |
| 46 |
if cache_dir is None and Cython is not None: |
| 47 |
cache_dir = os.path.join(base_cython_cache_dir(), "brian_extensions") |
| 48 |
return cache_dir |
| 49 |
|
| 50 |
|
| 51 |
def get_cython_extensions(): |
| 52 |
return { |
| 53 |
".pyx", |
| 54 |
".pxd", |
| 55 |
".pyd", |
| 56 |
".cpp", |
| 57 |
".c", |
| 58 |
".so", |
| 59 |
".o", |
| 60 |
".o.d", |
| 61 |
".lock", |
| 62 |
".dll", |
| 63 |
".obj", |
| 64 |
".exp", |
| 65 |
".lib", |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
class CythonExtensionManager: |
| 70 |
def __init__(self): |
| 71 |
self._code_cache = {} |
| 72 |
|
| 73 |
def create_extension( |
| 74 |
self, |
| 75 |
code, |
| 76 |
force=False, |
| 77 |
name=None, |
| 78 |
define_macros=None, |
| 79 |
include_dirs=None, |
| 80 |
library_dirs=None, |
| 81 |
runtime_library_dirs=None, |
| 82 |
extra_compile_args=None, |
| 83 |
extra_link_args=None, |
| 84 |
libraries=None, |
| 85 |
compiler=None, |
| 86 |
sources=None, |
| 87 |
owner_name="", |
| 88 |
): |
| 89 |
if sources is None: |
| 90 |
sources = [] |
| 91 |
self._simplify_paths() |
| 92 |
|
| 93 |
if Cython is None: |
| 94 |
raise ImportError("Cython is not available") |
| 95 |
|
| 96 |
code = deindent(code) |
| 97 |
|
| 98 |
lib_dir = get_cython_cache_dir() |
| 99 |
if "~" in lib_dir: |
| 100 |
lib_dir = os.path.expanduser(lib_dir) |
| 101 |
try: |
| 102 |
os.makedirs(lib_dir) |
| 103 |
except OSError as ex: |
| 104 |
if not os.path.exists(lib_dir): |
| 105 |
raise OSError( |
| 106 |
f"Couldn't create Cython cache directory '{lib_dir}', try setting" |
| 107 |
" the cache directly with prefs.codegen.runtime.cython.cache_dir." |
| 108 |
) from ex |
| 109 |
|
| 110 |
numpy_version = ".".join( |
| 111 |
numpy.__version__.split(".")[:2] |
| 112 |
) # Only use major.minor version |
| 113 |
# avoid some issues when manually switching compilers |
| 114 |
CC = os.environ.get("CC", None) |
| 115 |
CXX = os.environ.get("CXX", None) |
| 116 |
key = ( |
| 117 |
code, |
| 118 |
sys.version_info, |
| 119 |
sys.executable, |
| 120 |
Cython.__version__, |
| 121 |
numpy_version, |
| 122 |
CC, |
| 123 |
CXX, |
| 124 |
) |
| 125 |
|
| 126 |
if force: |
| 127 |
# Force a new module name by adding the current time to the |
| 128 |
# key which is hashed to determine the module name. |
| 129 |
key += (time.time(),) # Note the trailing comma (this is a tuple) |
| 130 |
|
| 131 |
if key in self._code_cache: |
| 132 |
return self._code_cache[key] |
| 133 |
|
| 134 |
if name is not None: |
| 135 |
module_name = name # py3compat.unicode_to_str(args.name) |
| 136 |
else: |
| 137 |
module_name = ( |
| 138 |
f"_cython_magic_{hashlib.md5(str(key).encode('utf-8')).hexdigest()}" |
| 139 |
) |
| 140 |
if owner_name: |
| 141 |
logger.diagnostic(f'"{owner_name}" using Cython module "{module_name}"') |
| 142 |
|
| 143 |
module_path = os.path.join(lib_dir, module_name + self.so_ext) |
| 144 |
|
| 145 |
if prefs["codegen.runtime.cython.multiprocess_safe"]: |
| 146 |
lock = FileLock(os.path.join(lib_dir, f"{module_name}.lock")) |
| 147 |
with lock: |
| 148 |
module = self._load_module( |
| 149 |
module_path, |
| 150 |
define_macros=define_macros, |
| 151 |
include_dirs=include_dirs, |
| 152 |
library_dirs=library_dirs, |
| 153 |
extra_compile_args=extra_compile_args, |
| 154 |
extra_link_args=extra_link_args, |
| 155 |
libraries=libraries, |
| 156 |
code=code, |
| 157 |
lib_dir=lib_dir, |
| 158 |
module_name=module_name, |
| 159 |
runtime_library_dirs=runtime_library_dirs, |
| 160 |
compiler=compiler, |
| 161 |
key=key, |
| 162 |
sources=sources, |
| 163 |
) |
| 164 |
return module |
| 165 |
else: |
| 166 |
return self._load_module( |
| 167 |
module_path, |
| 168 |
define_macros=define_macros, |
| 169 |
include_dirs=include_dirs, |
| 170 |
library_dirs=library_dirs, |
| 171 |
extra_compile_args=extra_compile_args, |
| 172 |
extra_link_args=extra_link_args, |
| 173 |
libraries=libraries, |
| 174 |
code=code, |
| 175 |
lib_dir=lib_dir, |
| 176 |
module_name=module_name, |
| 177 |
runtime_library_dirs=runtime_library_dirs, |
| 178 |
compiler=compiler, |
| 179 |
key=key, |
| 180 |
sources=sources, |
| 181 |
) |
| 182 |
|
| 183 |
@property |
| 184 |
def so_ext(self): |
| 185 |
"""The extension suffix for compiled modules.""" |
| 186 |
try: |
| 187 |
return self._so_ext |
| 188 |
except AttributeError: |
| 189 |
self._so_ext = self._get_build_extension().get_ext_filename("") |
| 190 |
return self._so_ext |
| 191 |
|
| 192 |
def _clear_distutils_mkpath_cache(self): |
| 193 |
"""clear distutils mkpath cache |
| 194 |
|
| 195 |
prevents distutils from skipping re-creation of dirs that have been removed |
| 196 |
""" |
| 197 |
try: |
| 198 |
from distutils.dir_util import _path_created |
| 199 |
except ImportError: |
| 200 |
pass |
| 201 |
else: |
| 202 |
_path_created.clear() |
| 203 |
|
| 204 |
def _get_build_extension(self, compiler=None): |
| 205 |
self._clear_distutils_mkpath_cache() |
| 206 |
dist = Distribution() |
| 207 |
config_files = dist.find_config_files() |
| 208 |
try: |
| 209 |
config_files.remove("setup.cfg") |
| 210 |
except ValueError: |
| 211 |
pass |
| 212 |
dist.parse_config_files(config_files) |
| 213 |
build_extension = build_ext(dist) |
| 214 |
if compiler is not None: |
| 215 |
build_extension.compiler = compiler |
| 216 |
build_extension.finalize_options() |
| 217 |
return build_extension |
| 218 |
|
| 219 |
def _load_module( |
| 220 |
self, |
| 221 |
module_path, |
| 222 |
define_macros, |
| 223 |
include_dirs, |
| 224 |
library_dirs, |
| 225 |
extra_compile_args, |
| 226 |
extra_link_args, |
| 227 |
libraries, |
| 228 |
code, |
| 229 |
lib_dir, |
| 230 |
module_name, |
| 231 |
runtime_library_dirs, |
| 232 |
compiler, |
| 233 |
key, |
| 234 |
sources, |
| 235 |
): |
| 236 |
have_module = os.path.isfile(module_path) |
| 237 |
|
| 238 |
if not have_module: |
| 239 |
if define_macros is None: |
| 240 |
define_macros = [] |
| 241 |
if include_dirs is None: |
| 242 |
include_dirs = [] |
| 243 |
if library_dirs is None: |
| 244 |
library_dirs = [] |
| 245 |
if runtime_library_dirs is None: |
| 246 |
runtime_library_dirs = [] |
| 247 |
if extra_compile_args is None: |
| 248 |
extra_compile_args = [] |
| 249 |
if extra_link_args is None: |
| 250 |
extra_link_args = [] |
| 251 |
if libraries is None: |
| 252 |
libraries = [] |
| 253 |
|
| 254 |
c_include_dirs = include_dirs |
| 255 |
if "numpy" in code: |
| 256 |
import numpy |
| 257 |
|
| 258 |
c_include_dirs.append(numpy.get_include()) |
| 259 |
|
| 260 |
# TODO: We should probably have a special folder just for header |
| 261 |
# files that are shared between different codegen targets |
| 262 |
import brian2.synapses as synapses |
| 263 |
|
| 264 |
synapses_dir = os.path.dirname(synapses.__file__) |
| 265 |
c_include_dirs.append(synapses_dir) |
| 266 |
|
| 267 |
import brian2 |
| 268 |
|
| 269 |
brian2_base_dir = os.path.dirname(brian2.__file__) |
| 270 |
brianlib_dir = os.path.join( |
| 271 |
brian2_base_dir, "devices", "cpp_standalone", "brianlib" |
| 272 |
) |
| 273 |
c_include_dirs.append(brianlib_dir) |
| 274 |
pyx_file = os.path.join(lib_dir, f"{module_name}.pyx") |
| 275 |
# ignore Python 3 unicode stuff for the moment |
| 276 |
# pyx_file = py3compat.cast_bytes_py2(pyx_file, encoding=sys.getfilesystemencoding()) |
| 277 |
# with io.open(pyx_file, 'w', encoding='utf-8') as f: |
| 278 |
# f.write(code) |
| 279 |
with open(pyx_file, "w") as f: |
| 280 |
f.write(code) |
| 281 |
|
| 282 |
for source in sources: |
| 283 |
if not source.lower().endswith(".pyx"): |
| 284 |
raise ValueError( |
| 285 |
"Additional Cython source files need to have an .pyx ending" |
| 286 |
) |
| 287 |
# Copy source and header file (if present) to library directory |
| 288 |
shutil.copyfile(source, os.path.join(lib_dir, os.path.basename(source))) |
| 289 |
name_without_ext = os.path.splitext(os.path.basename(source))[0] |
| 290 |
header_name = f"{name_without_ext}.pxd" |
| 291 |
if os.path.exists(os.path.join(os.path.dirname(source), header_name)): |
| 292 |
shutil.copyfile( |
| 293 |
os.path.join(os.path.dirname(source), header_name), |
| 294 |
os.path.join(lib_dir, header_name), |
| 295 |
) |
| 296 |
final_sources = [ |
| 297 |
os.path.join(lib_dir, os.path.basename(source)) for source in sources |
| 298 |
] |
| 299 |
extension = Extension( |
| 300 |
name=module_name, |
| 301 |
sources=[pyx_file], |
| 302 |
define_macros=define_macros, |
| 303 |
include_dirs=c_include_dirs, |
| 304 |
library_dirs=library_dirs, |
| 305 |
runtime_library_dirs=runtime_library_dirs, |
| 306 |
extra_compile_args=extra_compile_args, |
| 307 |
extra_link_args=extra_link_args, |
| 308 |
libraries=libraries, |
| 309 |
language="c++", |
| 310 |
) |
| 311 |
build_extension = self._get_build_extension(compiler=compiler) |
| 312 |
try: |
| 313 |
opts = dict( |
| 314 |
quiet=True, |
| 315 |
annotate=False, |
| 316 |
force=True, |
| 317 |
) |
| 318 |
# suppresses the output on stdout |
| 319 |
with std_silent(): |
| 320 |
build_extension.extensions = Cython_Build.cythonize( |
| 321 |
[extension] + final_sources, **opts |
| 322 |
) |
| 323 |
|
| 324 |
build_extension.build_temp = os.path.dirname(pyx_file) |
| 325 |
build_extension.build_lib = lib_dir |
| 326 |
build_extension.run() |
| 327 |
if prefs["codegen.runtime.cython.delete_source_files"]: |
| 328 |
# we can delete the source files to save disk space |
| 329 |
cpp_file = os.path.join(lib_dir, f"{module_name}.cpp") |
| 330 |
try: |
| 331 |
os.remove(pyx_file) |
| 332 |
os.remove(cpp_file) |
| 333 |
temp_dir = os.path.join( |
| 334 |
lib_dir, |
| 335 |
os.path.dirname(pyx_file)[1:], |
| 336 |
f"{module_name}.*", |
| 337 |
) |
| 338 |
for fname in glob.glob(temp_dir): |
| 339 |
os.remove(fname) |
| 340 |
except OSError as ex: |
| 341 |
logger.debug( |
| 342 |
"Deleting Cython source files failed with error:" |
| 343 |
f" {str(ex)}" |
| 344 |
) |
| 345 |
|
| 346 |
except Cython_Compiler.Errors.CompileError: |
| 347 |
return |
| 348 |
# Temporarily insert the Cython directory to the Python path so that |
| 349 |
# code importing from an external module that was declared via |
| 350 |
# sources works |
| 351 |
sys.path.insert(0, lib_dir) |
| 352 |
spec = importlib.util.spec_from_file_location(module_name, module_path) |
| 353 |
module = importlib.util.module_from_spec(spec) |
| 354 |
spec.loader.exec_module(module) |
| 355 |
sys.path.pop(0) |
| 356 |
self._code_cache[key] = module |
| 357 |
return module |
| 358 |
|
| 359 |
def _simplify_paths(self): |
| 360 |
if "lib" in os.environ: |
| 361 |
os.environ["lib"] = simplify_path_env_var(os.environ["lib"]) |
| 362 |
if "include" in os.environ: |
| 363 |
os.environ["include"] = simplify_path_env_var(os.environ["include"]) |
| 364 |
|
| 365 |
|
| 366 |
cython_extension_manager = CythonExtensionManager() |
| 367 |
|
| 368 |
|
| 369 |
def simplify_path_env_var(path): |
| 370 |
allpaths = path.split(os.pathsep) |
| 371 |
knownpaths = set() |
| 372 |
uniquepaths = [] |
| 373 |
for p in allpaths: |
| 374 |
if p not in knownpaths: |
| 375 |
knownpaths.add(p) |
| 376 |
uniquepaths.append(p) |
| 377 |
return os.pathsep.join(uniquepaths) |