Debian Codegraph @

setup.py

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