Debian Codegraph @

setup.py

raw ◀ ▶
Source reconstructed at patch state 3 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.libraries += ['zstd']
239 ext.define_macros += [("ZSTD_SUPPORT", 1)]
240
241
242 class develop(develop_):
243 def run(self):
244 # Dummy directory for copying build plugins.
245 if not path.isdir("bitshuffle/plugin"):
246 os.mkdir("bitshuffle/plugin")
247 develop_.run(self)
248
249
250 # Custom installation to include installing dynamic filters.
251 class install(install_):
252 user_options = install_.user_options + [
253 ("h5plugin", None, "Install HDF5 filter plugins for use outside of python."),
254 (
255 "h5plugin-dir=",
256 None,
257 "Where to install filter plugins. Default %s." % H5PLUGINS_DEFAULT,
258 ),
259 ("zstd", None, "Install ZSTD support."),
260 ]
261
262 def initialize_options(self):
263 install_.initialize_options(self)
264 self.h5plugin = False
265 self.zstd = False
266 self.h5plugin_dir = H5PLUGINS_DEFAULT
267
268 def finalize_options(self):
269 install_.finalize_options(self)
270 if self.h5plugin not in ("0", "1", True, False):
271 raise ValueError("Invalid h5plugin argument. Must be '0' or '1'.")
272 self.h5plugin = int(self.h5plugin)
273 self.h5plugin_dir = path.abspath(self.h5plugin_dir)
274 self.zstd = self.zstd
275
276 # Add ZSTD files and macro to extensions if ZSTD enabled
277 if self.zstd:
278 default_options["compile_time_env"] = {"ZSTD_SUPPORT": True}
279 for ext in EXTENSIONS:
280 if ext.name in [
281 "bitshuffle.ext",
282 "bitshuffle.h5",
283 "bitshuffle.plugin.libh5bshuf",
284 ]:
285 ext.sources += zstd_sources
286 ext.include_dirs += zstd_lib
287 ext.depends += zstd_headers
288 ext.define_macros += [("ZSTD_SUPPORT", 1)]
289
290 def run(self):
291 install_.run(self)
292 if self.h5plugin:
293 if not HDF5_PLUGIN_SUPPORT:
294 print("HDF5 < 1.8.11, not installing filter plugins.")
295 return
296 plugin_build = path.join(self.build_lib, "bitshuffle", "plugin")
297 try:
298 os.makedirs(self.h5plugin_dir)
299 except OSError as e:
300 if e.args[0] == 17:
301 # Directory already exists, this is fine.
302 pass
303 else:
304 raise
305 plugin_libs = glob.glob(path.join(plugin_build, "*"))
306 for plugin_lib in plugin_libs:
307 plugin_name = path.split(plugin_lib)[1]
308 shutil.copy2(plugin_lib, path.join(self.h5plugin_dir, plugin_name))
309 print("Installed HDF5 filter plugins to %s" % self.h5plugin_dir)
310
311
312 # Command line or site.cfg specification of OpenMP.
313 class build_ext(build_ext_):
314 user_options = build_ext_.user_options + [
315 (
316 "omp=",
317 None,
318 "Whether to compile with OpenMP threading. Default"
319 " on current system is %s." % str(OMP_DEFAULT),
320 ),
321 (
322 "march=",
323 None,
324 "Generate instructions for a specific machine type. Default is %s."
325 % MARCH_DEFAULT,
326 ),
327 ]
328 boolean_options = build_ext_.boolean_options + ["omp"]
329
330 def initialize_options(self):
331 build_ext_.initialize_options(self)
332 self.omp = OMP_DEFAULT
333 self.march = MARCH_DEFAULT
334
335 def finalize_options(self):
336 # For some reason this gets run twice. Careful to print messages and
337 # add arguments only one time.
338 build_ext_.finalize_options(self)
339
340 if self.omp not in ("0", "1", True, False):
341 raise ValueError("Invalid omp argument. Mut be '0' or '1'.")
342 self.omp = int(self.omp)
343
344 import numpy as np
345
346 ext_bshuf.include_dirs.append(np.get_include())
347
348 # Required only by old version of setuptools < 18.0
349 from Cython.Build import cythonize
350
351 self.extensions = cythonize(self.extensions)
352 for ext in self.extensions:
353 ext._needs_stub = False
354
355 def build_extensions(self):
356 # Set compiler flags including architecture
357 if self.compiler.compiler_type == "msvc":
358 openmpflag = "/openmp"
359 compileflags = COMPILE_FLAGS_MSVC
360 else:
361 openmpflag = "-fopenmp"
362 archi = platform.machine()
363 if archi in ("i386", "x86_64"):
364 compileflags = COMPILE_FLAGS + ["-march=%s" % self.march]
365 else:
366 compileflags = COMPILE_FLAGS + ["-mcpu=%s" % self.march]
367 if archi == "ppc64le":
368 compileflags = COMPILE_FLAGS + ["-DNO_WARN_X86_INTRINSICS"]
369
370 if self.omp not in ("0", "1", True, False):
371 raise ValueError("Invalid omp argument. Mut be '0' or '1'.")
372 self.omp = int(self.omp)
373
374 # Add the appropriate OpenMP flags if needed
375 if self.omp:
376 if not hasattr(self, "_printed_omp_message"):
377 self._printed_omp_message = True
378 print("\n#################################")
379 print("# Compiling with OpenMP support #")
380 print("#################################\n")
381 # More portable to pass -fopenmp to linker.
382 # self.libraries += ['gomp']
383 compileflags += [openmpflag]
384 linkflags = [openmpflag]
385 else:
386 linkflags = []
387
388 # Add the compile/link options to each extension
389 for e in self.extensions:
390 e.extra_compile_args = list(set(e.extra_compile_args).union(compileflags))
391 e.extra_link_args = list(set(e.extra_link_args).union(linkflags))
392
393 build_ext_.build_extensions(self)
394
395
396 # Don't install numpy/cython/hdf5 if not needed
397 for cmd in ["sdist", "clean", "--help", "--help-commands", "--version"]:
398 if cmd in sys.argv:
399 setup_requires = []
400 break
401 else:
402 setup_requires = ["Cython>=0.19", "numpy>=1.6.1"]
403
404 with open("requirements.txt") as f:
405 requires = f.read().splitlines()
406 requires = [r.split()[0] for r in requires]
407
408 with open("README.rst") as r:
409 long_description = r.read()
410
411 # TODO hdf5 support should be an "extra". Figure out how to set this up.
412 setup(
413 name="bitshuffle",
414 version=VERSION,
415 packages=["bitshuffle", "bitshuffle"],
416 scripts=[],
417 ext_modules=EXTENSIONS,
418 cmdclass={"build_ext": build_ext, "install": install, "develop": develop},
419 setup_requires=setup_requires,
420 install_requires=requires,
421 python_requires=">=3.9",
422 # extras_require={'H5': ["h5py"]},
423 package_data={"": ["data/*"]},
424 # metadata for upload to PyPI
425 author="Kiyoshi Wesley Masui",
426 author_email="[email protected]",
427 description="Bitshuffle filter for improving typed data compression.",
428 long_description=long_description,
429 license="MIT",
430 url="https://github.com/kiyo-masui/bitshuffle",
431 download_url=("https://github.com/kiyo-masui/bitshuffle/tarball/%s" % VERSION),
432 keywords=["compression", "hdf5", "numpy"],
433 )