Debian Codegraph @

setup.py

raw ◀ ▶
Source reconstructed at patch state 1 of 6 — not the installed (fully patched) source.
6 Debian patches touch this file
1 from __future__ import absolute_import, division, print_function
2
3 # I didn't import unicode_literals. They break setuptools or Cython in python
4 # 2.7, but python 3 seems to be happy with them.
5
6 import glob
7 import os
8 from os import path
9 from setuptools import setup, Extension
10 from setuptools.command.build_ext import build_ext as build_ext_
11 from setuptools.command.develop import develop as develop_
12 from setuptools.command.install import install as install_
13 from Cython.Compiler.Main import default_options
14 import shutil
15 import subprocess
16 import sys
17 import platform
18
19
20 VERSION_MAJOR = 0
21 VERSION_MINOR = 5
22 VERSION_POINT = 2
23 # Define ZSTD macro for cython compilation
24 default_options["compile_time_env"] = {"ZSTD_SUPPORT": False}
25
26 # Only unset in the 'release' branch and in tags.
27 VERSION_DEV = None
28
29 VERSION = "%d.%d.%d" % (VERSION_MAJOR, VERSION_MINOR, VERSION_POINT)
30 if VERSION_DEV:
31 VERSION = VERSION + ".dev%d" % VERSION_DEV
32
33
34 COMPILE_FLAGS = ["-O3", "-ffast-math", "-std=c99"]
35 # Cython breaks strict aliasing rules.
36 COMPILE_FLAGS += ["-fno-strict-aliasing"]
37 COMPILE_FLAGS += ["-fPIC"]
38 COMPILE_FLAGS_MSVC = ["/Ox", "/fp:fast"]
39
40 MACROS = [
41 ("BSHUF_VERSION_MAJOR", VERSION_MAJOR),
42 ("BSHUF_VERSION_MINOR", VERSION_MINOR),
43 ("BSHUF_VERSION_POINT", VERSION_POINT),
44 ]
45
46
47 H5PLUGINS_DEFAULT = "/usr/local/hdf5/lib/plugin"
48
49 # OSX's clang compiler does not support OpenMP.
50 if sys.platform == "darwin":
51 OMP_DEFAULT = False
52 else:
53 OMP_DEFAULT = True
54
55 # Build against the native architecture unless overridden by an environment variable
56 # This can also be overridden by a direct command line argument, or a `setup.cfg` entry
57 # This option is needed for the cibuildwheel action
58 if "BITSHUFFLE_ARCH" in os.environ:
59 MARCH_DEFAULT = os.environ["BITSHUFFLE_ARCH"]
60 else:
61 MARCH_DEFAULT = "native"
62
63 FALLBACK_CONFIG = {
64 "include_dirs": [],
65 "library_dirs": [],
66 "libraries": [],
67 "extra_compile_args": [],
68 "extra_link_args": [],
69 }
70
71 if "HDF5_DIR" in os.environ:
72 FALLBACK_CONFIG["include_dirs"] += [os.environ["HDF5_DIR"] + "/include"] # macports
73 FALLBACK_CONFIG["library_dirs"] += [os.environ["HDF5_DIR"] + "/lib"] # macports
74 elif sys.platform == "darwin":
75 # putting here both macports and homebrew paths will generate
76 # "ld: warning: dir not found" at the linking phase
77 FALLBACK_CONFIG["include_dirs"] += ["/opt/local/include"] # macports
78 FALLBACK_CONFIG["library_dirs"] += ["/opt/local/lib"] # macports
79 FALLBACK_CONFIG["include_dirs"] += ["/usr/local/include"] # homebrew
80 FALLBACK_CONFIG["library_dirs"] += ["/usr/local/lib"] # homebrew
81 elif sys.platform.startswith("freebsd"):
82 FALLBACK_CONFIG["include_dirs"] += ["/usr/local/include"] # homebrew
83 FALLBACK_CONFIG["library_dirs"] += ["/usr/local/lib"] # homebrew
84
85 FALLBACK_CONFIG["include_dirs"] = [
86 d for d in FALLBACK_CONFIG["include_dirs"] if path.isdir(d)
87 ]
88 FALLBACK_CONFIG["library_dirs"] = [
89 d for d in FALLBACK_CONFIG["library_dirs"] if path.isdir(d)
90 ]
91
92 FALLBACK_CONFIG["extra_compile_args"] = ["-DH5_BUILT_AS_DYNAMIC_LIB"]
93
94
95 def pkgconfig(*packages, **kw):
96 config = kw.setdefault("config", {})
97 optional_args = kw.setdefault("optional", "")
98 flag_map = {
99 "include_dirs": ["--cflags-only-I", 2],
100 "library_dirs": ["--libs-only-L", 2],
101 "libraries": ["--libs-only-l", 2],
102 "extra_compile_args": ["--cflags-only-other", 0],
103 "extra_link_args": ["--libs-only-other", 0],
104 }
105 for package in packages:
106 try:
107 subprocess.check_output(["pkg-config", package])
108 except (subprocess.CalledProcessError, OSError):
109 print("Can't find %s with pkg-config fallback to static config" % package)
110 for distutils_key in flag_map:
111 config.setdefault(distutils_key, []).extend(
112 FALLBACK_CONFIG[distutils_key]
113 )
114 config["libraries"].append(package)
115 else:
116 for distutils_key, (pkg_option, n) in flag_map.items():
117 items = (
118 subprocess.check_output(
119 ["pkg-config", optional_args, pkg_option, package]
120 )
121 .decode("utf8")
122 .split()
123 )
124 opt = config.setdefault(distutils_key, [])
125 opt.extend([i[n:] for i in items])
126 return config
127
128
129 zstd_headers = ["zstd/lib/zstd.h"]
130 zstd_lib = ["zstd/lib/"]
131 zstd_sources = glob.glob("zstd/lib/common/*.c")
132 zstd_sources += glob.glob("zstd/lib/compress/*.c")
133 zstd_sources += glob.glob("zstd/lib/decompress/*.c")
134
135 ext_bshuf = Extension(
136 "bitshuffle.ext",
137 sources=[
138 "bitshuffle/ext.pyx",
139 "src/bitshuffle.c",
140 "src/bitshuffle_core.c",
141 "src/iochain.c",
142 "lz4/lz4.c",
143 ],
144 include_dirs=["src/", "lz4/"],
145 depends=["src/bitshuffle.h", "src/bitshuffle_core.h", "src/iochain.h", "lz4/lz4.h"],
146 libraries=[],
147 define_macros=MACROS,
148 )
149
150 h5filter = Extension(
151 "bitshuffle.h5",
152 sources=[
153 "bitshuffle/h5.pyx",
154 "src/bshuf_h5filter.c",
155 "src/bitshuffle.c",
156 "src/bitshuffle_core.c",
157 "src/iochain.c",
158 "lz4/lz4.c",
159 ],
160 depends=[
161 "src/bitshuffle.h",
162 "src/bitshuffle_core.h",
163 "src/iochain.h",
164 "src/bshuf_h5filter.h",
165 "lz4/lz4.h",
166 ],
167 define_macros=MACROS + [("H5_USE_18_API", None)],
168 **pkgconfig("hdf5", config=dict(include_dirs=["src/", "lz4/"]))
169 )
170
171 if not sys.platform.startswith("win"):
172 h5filter.sources.append("src/hdf5_dl.c")
173 h5filter.libraries.remove("hdf5")
174
175 filter_plugin = Extension(
176 "bitshuffle.plugin.libh5bshuf",
177 sources=[
178 "src/bshuf_h5plugin.c",
179 "src/bshuf_h5filter.c",
180 "src/bitshuffle.c",
181 "src/bitshuffle_core.c",
182 "src/iochain.c",
183 "lz4/lz4.c",
184 ],
185 depends=[
186 "src/bitshuffle.h",
187 "src/bitshuffle_core.h",
188 "src/iochain.h",
189 "src/bshuf_h5filter.h",
190 "lz4/lz4.h",
191 ],
192 define_macros=MACROS,
193 **pkgconfig("hdf5", config=dict(include_dirs=["src/", "lz4/"]))
194 )
195
196 lzf_plugin = Extension(
197 "bitshuffle.plugin.libh5LZF",
198 sources=[
199 "src/lzf_h5plugin.c",
200 "lzf/lzf_filter.c",
201 ],
202 depends=["lzf/lzf_filter.h"],
203 **pkgconfig("hdf5", "liblzf", config=dict(include_dirs=["lzf/"]))
204 )
205
206
207 EXTENSIONS = [
208 ext_bshuf,
209 ]
210
211 # Check for HDF5 support
212 HDF5_FILTER_SUPPORT = False
213 CPATHS = os.environ["CPATH"].split(":") if "CPATH" in os.environ else []
214 for p in ["/usr/include"] + pkgconfig("hdf5")["include_dirs"] + CPATHS:
215 if os.path.exists(os.path.join(p, "hdf5.h")):
216 HDF5_FILTER_SUPPORT = True
217
218 if HDF5_FILTER_SUPPORT:
219 EXTENSIONS.append(h5filter)
220
221 # Check for plugin hdf5 plugin support (hdf5 >= 1.8.11)
222 HDF5_PLUGIN_SUPPORT = False
223 CPATHS = os.environ["CPATH"].split(":") if "CPATH" in os.environ else []
224 for p in ["/usr/include"] + pkgconfig("hdf5")["include_dirs"] + CPATHS:
225 if os.path.exists(os.path.join(p, "H5PLextern.h")):
226 HDF5_PLUGIN_SUPPORT = True
227
228 if HDF5_PLUGIN_SUPPORT:
229 EXTENSIONS.extend([filter_plugin, lzf_plugin])
230
231 # For enabling ZSTD support when building wheels
232 # This needs to be done after all Extensions have been added to EXTENSIONS
233 if "ENABLE_ZSTD" in os.environ:
234 default_options["compile_time_env"] = {"ZSTD_SUPPORT": True}
235 for ext in EXTENSIONS:
236 if ext.name in [
237 "bitshuffle.ext",
238 "bitshuffle.h5",
239 "bitshuffle.plugin.libh5bshuf",
240 ]:
241 ext.sources += zstd_sources
242 ext.include_dirs += zstd_lib
243 ext.depends += zstd_headers
244 ext.define_macros += [("ZSTD_SUPPORT", 1)]
245
246
247 class develop(develop_):
248 def run(self):
249 # Dummy directory for copying build plugins.
250 if not path.isdir("bitshuffle/plugin"):
251 os.mkdir("bitshuffle/plugin")
252 develop_.run(self)
253
254
255 # Custom installation to include installing dynamic filters.
256 class install(install_):
257 user_options = install_.user_options + [
258 ("h5plugin", None, "Install HDF5 filter plugins for use outside of python."),
259 (
260 "h5plugin-dir=",
261 None,
262 "Where to install filter plugins. Default %s." % H5PLUGINS_DEFAULT,
263 ),
264 ("zstd", None, "Install ZSTD support."),
265 ]
266
267 def initialize_options(self):
268 install_.initialize_options(self)
269 self.h5plugin = False
270 self.zstd = False
271 self.h5plugin_dir = H5PLUGINS_DEFAULT
272
273 def finalize_options(self):
274 install_.finalize_options(self)
275 if self.h5plugin not in ("0", "1", True, False):
276 raise ValueError("Invalid h5plugin argument. Must be '0' or '1'.")
277 self.h5plugin = int(self.h5plugin)
278 self.h5plugin_dir = path.abspath(self.h5plugin_dir)
279 self.zstd = self.zstd
280
281 # Add ZSTD files and macro to extensions if ZSTD enabled
282 if self.zstd:
283 default_options["compile_time_env"] = {"ZSTD_SUPPORT": True}
284 for ext in EXTENSIONS:
285 if ext.name in [
286 "bitshuffle.ext",
287 "bitshuffle.h5",
288 "bitshuffle.plugin.libh5bshuf",
289 ]:
290 ext.sources += zstd_sources
291 ext.include_dirs += zstd_lib
292 ext.depends += zstd_headers
293 ext.define_macros += [("ZSTD_SUPPORT", 1)]
294
295 def run(self):
296 install_.run(self)
297 if self.h5plugin:
298 if not HDF5_PLUGIN_SUPPORT:
299 print("HDF5 < 1.8.11, not installing filter plugins.")
300 return
301 plugin_build = path.join(self.build_lib, "bitshuffle", "plugin")
302 try:
303 os.makedirs(self.h5plugin_dir)
304 except OSError as e:
305 if e.args[0] == 17:
306 # Directory already exists, this is fine.
307 pass
308 else:
309 raise
310 plugin_libs = glob.glob(path.join(plugin_build, "*"))
311 for plugin_lib in plugin_libs:
312 plugin_name = path.split(plugin_lib)[1]
313 shutil.copy2(plugin_lib, path.join(self.h5plugin_dir, plugin_name))
314 print("Installed HDF5 filter plugins to %s" % self.h5plugin_dir)
315
316
317 # Command line or site.cfg specification of OpenMP.
318 class build_ext(build_ext_):
319 user_options = build_ext_.user_options + [
320 (
321 "omp=",
322 None,
323 "Whether to compile with OpenMP threading. Default"
324 " on current system is %s." % str(OMP_DEFAULT),
325 ),
326 (
327 "march=",
328 None,
329 "Generate instructions for a specific machine type. Default is %s."
330 % MARCH_DEFAULT,
331 ),
332 ]
333 boolean_options = build_ext_.boolean_options + ["omp"]
334
335 def initialize_options(self):
336 build_ext_.initialize_options(self)
337 self.omp = OMP_DEFAULT
338 self.march = MARCH_DEFAULT
339
340 def finalize_options(self):
341 # For some reason this gets run twice. Careful to print messages and
342 # add arguments only one time.
343 build_ext_.finalize_options(self)
344
345 if self.omp not in ("0", "1", True, False):
346 raise ValueError("Invalid omp argument. Mut be '0' or '1'.")
347 self.omp = int(self.omp)
348
349 import numpy as np
350
351 ext_bshuf.include_dirs.append(np.get_include())
352
353 # Required only by old version of setuptools < 18.0
354 from Cython.Build import cythonize
355
356 self.extensions = cythonize(self.extensions)
357 for ext in self.extensions:
358 ext._needs_stub = False
359
360 def build_extensions(self):
361 # Set compiler flags including architecture
362 if self.compiler.compiler_type == "msvc":
363 openmpflag = "/openmp"
364 compileflags = COMPILE_FLAGS_MSVC
365 else:
366 openmpflag = "-fopenmp"
367 archi = platform.machine()
368 if archi in ("i386", "x86_64"):
369 compileflags = COMPILE_FLAGS + ["-march=%s" % self.march]
370 else:
371 compileflags = COMPILE_FLAGS + ["-mcpu=%s" % self.march]
372 if archi == "ppc64le":
373 compileflags = COMPILE_FLAGS + ["-DNO_WARN_X86_INTRINSICS"]
374
375 if self.omp not in ("0", "1", True, False):
376 raise ValueError("Invalid omp argument. Mut be '0' or '1'.")
377 self.omp = int(self.omp)
378
379 # Add the appropriate OpenMP flags if needed
380 if self.omp:
381 if not hasattr(self, "_printed_omp_message"):
382 self._printed_omp_message = True
383 print("\n#################################")
384 print("# Compiling with OpenMP support #")
385 print("#################################\n")
386 # More portable to pass -fopenmp to linker.
387 # self.libraries += ['gomp']
388 compileflags += [openmpflag]
389 linkflags = [openmpflag]
390 else:
391 linkflags = []
392
393 # Add the compile/link options to each extension
394 for e in self.extensions:
395 e.extra_compile_args = list(set(e.extra_compile_args).union(compileflags))
396 e.extra_link_args = list(set(e.extra_link_args).union(linkflags))
397
398 build_ext_.build_extensions(self)
399
400
401 # Don't install numpy/cython/hdf5 if not needed
402 for cmd in ["sdist", "clean", "--help", "--help-commands", "--version"]:
403 if cmd in sys.argv:
404 setup_requires = []
405 break
406 else:
407 setup_requires = ["Cython>=0.19", "numpy>=1.6.1"]
408
409 with open("requirements.txt") as f:
410 requires = f.read().splitlines()
411 requires = [r.split()[0] for r in requires]
412
413 with open("README.rst") as r:
414 long_description = r.read()
415
416 # TODO hdf5 support should be an "extra". Figure out how to set this up.
417 setup(
418 name="bitshuffle",
419 version=VERSION,
420 packages=["bitshuffle", "bitshuffle"],
421 scripts=[],
422 ext_modules=EXTENSIONS,
423 cmdclass={"build_ext": build_ext, "install": install, "develop": develop},
424 setup_requires=setup_requires,
425 install_requires=requires,
426 python_requires=">=3.9",
427 # extras_require={'H5': ["h5py"]},
428 package_data={"": ["data/*"]},
429 # metadata for upload to PyPI
430 author="Kiyoshi Wesley Masui",
431 author_email="[email protected]",
432 description="Bitshuffle filter for improving typed data compression.",
433 long_description=long_description,
434 license="MIT",
435 url="https://github.com/kiyo-masui/bitshuffle",
436 download_url=("https://github.com/kiyo-masui/bitshuffle/tarball/%s" % VERSION),
437 keywords=["compression", "hdf5", "numpy"],
438 )