Debian Codegraph @

setup.py

raw ◀ ▶
Source reconstructed at patch state 2 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 ],
143 depends=["src/bitshuffle.h", "src/bitshuffle_core.h", "src/iochain.h"],
144 define_macros=MACROS,
145 **pkgconfig("liblz4", config=dict(include_dirs=["src/"]))
146 )
147
148 h5filter = Extension(
149 "bitshuffle.h5",
150 sources=[
151 "bitshuffle/h5.pyx",
152 "src/bshuf_h5filter.c",
153 "src/bitshuffle.c",
154 "src/bitshuffle_core.c",
155 "src/iochain.c",
156 ],
157 depends=[
158 "src/bitshuffle.h",
159 "src/bitshuffle_core.h",
160 "src/iochain.h",
161 "src/bshuf_h5filter.h",
162 ],
163 define_macros=MACROS + [("H5_USE_18_API", None)],
164 **pkgconfig("hdf5", "liblz4", config=dict(include_dirs=["src/"]))
165 )
166
167 if not sys.platform.startswith("win"):
168 h5filter.sources.append("src/hdf5_dl.c")
169 h5filter.libraries.remove("hdf5")
170
171 filter_plugin = Extension(
172 "bitshuffle.plugin.libh5bshuf",
173 sources=[
174 "src/bshuf_h5plugin.c",
175 "src/bshuf_h5filter.c",
176 "src/bitshuffle.c",
177 "src/bitshuffle_core.c",
178 "src/iochain.c",
179 ],
180 depends=[
181 "src/bitshuffle.h",
182 "src/bitshuffle_core.h",
183 "src/iochain.h",
184 "src/bshuf_h5filter.h",
185 ],
186 define_macros=MACROS,
187 **pkgconfig("hdf5", "liblz4", config=dict(include_dirs=["src/"]))
188 )
189
190 lzf_plugin = Extension(
191 "bitshuffle.plugin.libh5LZF",
192 sources=[
193 "src/lzf_h5plugin.c",
194 "lzf/lzf_filter.c",
195 ],
196 depends=["lzf/lzf_filter.h"],
197 **pkgconfig("hdf5", "liblzf", config=dict(include_dirs=["lzf/"]))
198 )
199
200
201 EXTENSIONS = [
202 ext_bshuf,
203 ]
204
205 # Check for HDF5 support
206 HDF5_FILTER_SUPPORT = False
207 CPATHS = os.environ["CPATH"].split(":") if "CPATH" in os.environ else []
208 for p in ["/usr/include"] + pkgconfig("hdf5")["include_dirs"] + CPATHS:
209 if os.path.exists(os.path.join(p, "hdf5.h")):
210 HDF5_FILTER_SUPPORT = True
211
212 if HDF5_FILTER_SUPPORT:
213 EXTENSIONS.append(h5filter)
214
215 # Check for plugin hdf5 plugin support (hdf5 >= 1.8.11)
216 HDF5_PLUGIN_SUPPORT = False
217 CPATHS = os.environ["CPATH"].split(":") if "CPATH" in os.environ else []
218 for p in ["/usr/include"] + pkgconfig("hdf5")["include_dirs"] + CPATHS:
219 if os.path.exists(os.path.join(p, "H5PLextern.h")):
220 HDF5_PLUGIN_SUPPORT = True
221
222 if HDF5_PLUGIN_SUPPORT:
223 EXTENSIONS.extend([filter_plugin, lzf_plugin])
224
225 # For enabling ZSTD support when building wheels
226 # This needs to be done after all Extensions have been added to EXTENSIONS
227 if "ENABLE_ZSTD" in os.environ:
228 default_options["compile_time_env"] = {"ZSTD_SUPPORT": True}
229 for ext in EXTENSIONS:
230 if ext.name in [
231 "bitshuffle.ext",
232 "bitshuffle.h5",
233 "bitshuffle.plugin.libh5bshuf",
234 ]:
235 ext.sources += zstd_sources
236 ext.include_dirs += zstd_lib
237 ext.depends += zstd_headers
238 ext.define_macros += [("ZSTD_SUPPORT", 1)]
239
240
241 class develop(develop_):
242 def run(self):
243 # Dummy directory for copying build plugins.
244 if not path.isdir("bitshuffle/plugin"):
245 os.mkdir("bitshuffle/plugin")
246 develop_.run(self)
247
248
249 # Custom installation to include installing dynamic filters.
250 class install(install_):
251 user_options = install_.user_options + [
252 ("h5plugin", None, "Install HDF5 filter plugins for use outside of python."),
253 (
254 "h5plugin-dir=",
255 None,
256 "Where to install filter plugins. Default %s." % H5PLUGINS_DEFAULT,
257 ),
258 ("zstd", None, "Install ZSTD support."),
259 ]
260
261 def initialize_options(self):
262 install_.initialize_options(self)
263 self.h5plugin = False
264 self.zstd = False
265 self.h5plugin_dir = H5PLUGINS_DEFAULT
266
267 def finalize_options(self):
268 install_.finalize_options(self)
269 if self.h5plugin not in ("0", "1", True, False):
270 raise ValueError("Invalid h5plugin argument. Must be '0' or '1'.")
271 self.h5plugin = int(self.h5plugin)
272 self.h5plugin_dir = path.abspath(self.h5plugin_dir)
273 self.zstd = self.zstd
274
275 # Add ZSTD files and macro to extensions if ZSTD enabled
276 if self.zstd:
277 default_options["compile_time_env"] = {"ZSTD_SUPPORT": True}
278 for ext in EXTENSIONS:
279 if ext.name in [
280 "bitshuffle.ext",
281 "bitshuffle.h5",
282 "bitshuffle.plugin.libh5bshuf",
283 ]:
284 ext.sources += zstd_sources
285 ext.include_dirs += zstd_lib
286 ext.depends += zstd_headers
287 ext.define_macros += [("ZSTD_SUPPORT", 1)]
288
289 def run(self):
290 install_.run(self)
291 if self.h5plugin:
292 if not HDF5_PLUGIN_SUPPORT:
293 print("HDF5 < 1.8.11, not installing filter plugins.")
294 return
295 plugin_build = path.join(self.build_lib, "bitshuffle", "plugin")
296 try:
297 os.makedirs(self.h5plugin_dir)
298 except OSError as e:
299 if e.args[0] == 17:
300 # Directory already exists, this is fine.
301 pass
302 else:
303 raise
304 plugin_libs = glob.glob(path.join(plugin_build, "*"))
305 for plugin_lib in plugin_libs:
306 plugin_name = path.split(plugin_lib)[1]
307 shutil.copy2(plugin_lib, path.join(self.h5plugin_dir, plugin_name))
308 print("Installed HDF5 filter plugins to %s" % self.h5plugin_dir)
309
310
311 # Command line or site.cfg specification of OpenMP.
312 class build_ext(build_ext_):
313 user_options = build_ext_.user_options + [
314 (
315 "omp=",
316 None,
317 "Whether to compile with OpenMP threading. Default"
318 " on current system is %s." % str(OMP_DEFAULT),
319 ),
320 (
321 "march=",
322 None,
323 "Generate instructions for a specific machine type. Default is %s."
324 % MARCH_DEFAULT,
325 ),
326 ]
327 boolean_options = build_ext_.boolean_options + ["omp"]
328
329 def initialize_options(self):
330 build_ext_.initialize_options(self)
331 self.omp = OMP_DEFAULT
332 self.march = MARCH_DEFAULT
333
334 def finalize_options(self):
335 # For some reason this gets run twice. Careful to print messages and
336 # add arguments only one time.
337 build_ext_.finalize_options(self)
338
339 if self.omp not in ("0", "1", True, False):
340 raise ValueError("Invalid omp argument. Mut be '0' or '1'.")
341 self.omp = int(self.omp)
342
343 import numpy as np
344
345 ext_bshuf.include_dirs.append(np.get_include())
346
347 # Required only by old version of setuptools < 18.0
348 from Cython.Build import cythonize
349
350 self.extensions = cythonize(self.extensions)
351 for ext in self.extensions:
352 ext._needs_stub = False
353
354 def build_extensions(self):
355 # Set compiler flags including architecture
356 if self.compiler.compiler_type == "msvc":
357 openmpflag = "/openmp"
358 compileflags = COMPILE_FLAGS_MSVC
359 else:
360 openmpflag = "-fopenmp"
361 archi = platform.machine()
362 if archi in ("i386", "x86_64"):
363 compileflags = COMPILE_FLAGS + ["-march=%s" % self.march]
364 else:
365 compileflags = COMPILE_FLAGS + ["-mcpu=%s" % self.march]
366 if archi == "ppc64le":
367 compileflags = COMPILE_FLAGS + ["-DNO_WARN_X86_INTRINSICS"]
368
369 if self.omp not in ("0", "1", True, False):
370 raise ValueError("Invalid omp argument. Mut be '0' or '1'.")
371 self.omp = int(self.omp)
372
373 # Add the appropriate OpenMP flags if needed
374 if self.omp:
375 if not hasattr(self, "_printed_omp_message"):
376 self._printed_omp_message = True
377 print("\n#################################")
378 print("# Compiling with OpenMP support #")
379 print("#################################\n")
380 # More portable to pass -fopenmp to linker.
381 # self.libraries += ['gomp']
382 compileflags += [openmpflag]
383 linkflags = [openmpflag]
384 else:
385 linkflags = []
386
387 # Add the compile/link options to each extension
388 for e in self.extensions:
389 e.extra_compile_args = list(set(e.extra_compile_args).union(compileflags))
390 e.extra_link_args = list(set(e.extra_link_args).union(linkflags))
391
392 build_ext_.build_extensions(self)
393
394
395 # Don't install numpy/cython/hdf5 if not needed
396 for cmd in ["sdist", "clean", "--help", "--help-commands", "--version"]:
397 if cmd in sys.argv:
398 setup_requires = []
399 break
400 else:
401 setup_requires = ["Cython>=0.19", "numpy>=1.6.1"]
402
403 with open("requirements.txt") as f:
404 requires = f.read().splitlines()
405 requires = [r.split()[0] for r in requires]
406
407 with open("README.rst") as r:
408 long_description = r.read()
409
410 # TODO hdf5 support should be an "extra". Figure out how to set this up.
411 setup(
412 name="bitshuffle",
413 version=VERSION,
414 packages=["bitshuffle", "bitshuffle"],
415 scripts=[],
416 ext_modules=EXTENSIONS,
417 cmdclass={"build_ext": build_ext, "install": install, "develop": develop},
418 setup_requires=setup_requires,
419 install_requires=requires,
420 python_requires=">=3.9",
421 # extras_require={'H5': ["h5py"]},
422 package_data={"": ["data/*"]},
423 # metadata for upload to PyPI
424 author="Kiyoshi Wesley Masui",
425 author_email="[email protected]",
426 description="Bitshuffle filter for improving typed data compression.",
427 long_description=long_description,
428 license="MIT",
429 url="https://github.com/kiyo-masui/bitshuffle",
430 download_url=("https://github.com/kiyo-masui/bitshuffle/tarball/%s" % VERSION),
431 keywords=["compression", "hdf5", "numpy"],
432 )