-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsetup.py
271 lines (228 loc) · 9.76 KB
/
setup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/python
###############################################################################
## setup.py
###############################################################################
##
## Setup file to build EMBEDR package.
##
## Author: Eric Johnson
## Date Last Modified: June 9, 2020
##
## This setup file is adapted from the openTSNE setup.py file written by
## Pavlin Poličar under the BSD 3-Clause License.
##
## The modifications to compile the ANNOY library were adapted from the
## setup file at github.com/spotify/annoy
##
###############################################################################
import distutils
import os
from os import path
import platform
import sys
import tempfile
import warnings
from distutils import ccompiler
from distutils.command.build_ext import build_ext
from distutils.errors import CompileError, LinkError
from distutils.sysconfig import customize_compiler
import setuptools
from setuptools import setup, Extension
class get_numpy_include:
"""Helper class to determine the numpy include path
The idea here is that we want to use ``numpy.get_include()``, but we can't
call it until we're sure numpy is installed.
"""
def __str__(self):
import numpy
return numpy.get_include()
def get_include_dirs():
"""Quick function to get include directories for the compiler"""
sysp = sys.prefix
return (path.join(sysp, "include"), path.join(sysp, "Library", "include"))
def get_library_dirs():
"""Quick function to get library directories for the compiler"""
sysp = sys.prefix
return (path.join(sysp, "lib"), path.join(sysp, "Library", "lib"))
def has_c_library(library, extension=".c"):
"""Check whether a C/C++ library is available to the compiler.
Parameters
----------
library: str
The name of the library that we want to check for. For example, if we
want FFTW3, then we need to link `fftw3.h`, so we supply `fftw3` as an
input to this function.
extensions: str (optional, default='.c')
File extension of the library we want to check for. If we want a C
library, then the extension is `.c`, while for C++, any of `.cc`,
`.cpp`, or `.cxx` are allowed.
Returns
-------
bool
T/F depending on whether the requested library is available.
"""
with tempfile.TemporaryDirectory(dir=".") as directory:
## Make a temporary C/C++ file that looks for the requested library.
fname = path.join(directory, f"{library}{extension}")
with open(fname, "w") as f:
f.write(f"#include <{library}.h>\n")
f.write("int main() {}\n")
## Get a compiler
compiler = ccompiler.new_compiler()
customize_compiler(compiler)
## Add the include directories
for inc_dir in get_include_dirs():
compiler.add_include_dir(inc_dir)
## I don't know why we need this assertion.
assert isinstance(compiler, ccompiler.CCompiler)
## Try to compile and link the library
try:
compiler.link_executable(compiler.compile([fname]), fname)
return True
except (CompileError, LinkError):
return False
class MyBuildExt(build_ext):
def build_extensions(self):
## We need to add a few things to the extension builder to keep track
## of the system architecture and to correctly compile the Annoy lib.
## First, lets set up compile and linker arguments
extra_compile_args = []
extra_link_args = []
## Depending on the compiler, set the optimization level
compiler = self.compiler.compiler_type
if compiler == 'unix':
extra_compile_args += ["-O3"]
elif compiler == 'msvc':
extra_compile_args += ["/Ox", "/fp:fast"]
## Poličar: "For some reason fast math causes segfaults on linus but
## works on mac"
if compiler == 'unix' and platform.system() == 'Darwin':
extra_compile_args += ["-ffast-math", "-fno-associative-math"]
## Make sure that the Annoy library can be found:
annoy_ext = None
for extension in extensions:
if "annoy.annoylib" in extension.name:
annoy_ext = extension
assert annoy_ext is not None, "Annoy extension could not be found!"
## Then we set up Annoy-specific flags
if compiler == 'unix':
annoy_ext.extra_compile_args += ["-std=c++14"]
annoy_ext.extra_compile_args += ["-DANNOYLIB_MULTITHREADED_BUILD"]
elif compiler == 'msvc':
annoy_ext.extra_compile_args += ["/std:c++14"]
## Set the minimum MacOS version
if compiler == 'unix' and platform.system() == "Darwin":
extra_compile_args += ['-mmacosx-version-min=10.12']
extra_link_args += ["-stdlib=libc++",
"-mmacosx-version-min=10.12"]
## Poličar: "We don't want the compiler to optimize for system
## architecture if we're building packages to be distributed by
## conda-forge, but if the package is being built locally, this is
## desired." Basically if we know what system we're on, we can do some
## further optimization.
if not ("AZURE_BUILD" in os.environ or "CONDA_BUILD" in os.environ):
if platform.machine() == 'ppc64le':
extra_compile_args += ['-mpcu=native']
if platform.machine() == 'x86_64':
extra_compile_args += ['-march=native']
## Check for omp library. Add compiler flags if it's found.
if has_c_library("omp"):
print(f"Found openMP. Compiling with openmp flags...")
if platform.system() == "Darwin" and compiler == 'unix':
extra_compile_args += ["-Xpreprocessor", "-fopenmp"]
extra_link_args += ['-lomp']
elif compiler == 'unix':
extra_compile_args += ['-fopenmp']
extra_link_args += ['-fopenmp']
elif compiler == 'msvc':
extra_compile_args += ['/openmp']
extra_link_args += ['/openmp']
else:
warn_str = f"You appear to be using a compiler that does not"
warn_str += f" support openMP, meaning that this library will not"
warn_str += f" be able to run on multiple cores. Please install or"
warn_str += f" enable openMP to use multiple cores."
warnings.warn(warn_str)
## Add other arguments that might be defined.
for extension in extensions:
extension.extra_compile_args += extra_compile_args
extension.extra_link_args += extra_link_args
## Add the numpy and system include and library directories
for extension in extensions:
extension.include_dirs.extend(get_include_dirs())
extension.include_dirs.append(get_numpy_include())
extension.library_dirs.extend(get_library_dirs())
## Run the super method.
super().build_extensions()
## Prepare the Annoy extension.
## This is adapted from the annoy setup.py
extra_compile_args = []
extra_link_args = []
annoy_path = "EMBEDR/dependencies/annoy/"
annoy_hdrs = ["annoylib.h", "kissrandom.h", "mman.h"]
annoy_ext = Extension("EMBEDR.dependencies.annoy.annoylib",
[annoy_path + "annoymodule.cc"],
depends=[annoy_path + f for f in annoy_hdrs],
language="c++",
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args)
## Prepare the quad_tree extension.
quad_tree_ext = Extension("EMBEDR.quad_tree",
["EMBEDR/quad_tree.pyx"],
language="c++")
## Prepare the _tsne extension.
_tSNE_ext = Extension("EMBEDR._tsne", ["EMBEDR/_tsne.pyx"], language="c++")
## All the extensions together
extensions = [quad_tree_ext, _tSNE_ext, annoy_ext]
## To do the Fourier convolutions we need either fftw3 or to use numpy...
if has_c_library("fftw3"):
print(f"FFTW3 header files found. Using the FFTW implementation of FFT.")
fftw3_ext = Extension("EMBEDR._matrix_mul.matrix_mul",
["EMBEDR/_matrix_mul/matrix_mul_fftw3.pyx"],
libraries=["fftw3"],
language="c++",)
extensions.append(fftw3_ext)
else:
print(f"FFTW3 header files couldn't be found. Using numpy for FFT.")
numpy_ext = Extension("EMBEDR._matrix_mul.matrix_mul",
["EMBEDR/_matrix_mul/matrix_mul_numpy.pyx"],
language="c++",)
extensions.append(numpy_ext)
## Try and cythonize anything applicable.
try:
from Cython.Build import cythonize
extensions = cythonize(extensions)
except ImportError:
pass
# Read in version
__version__: str = "" ## This line suppresses linting errors.
exec(open(os.path.join("EMBEDR", "version.py")).read())
setup(
name="EMBEDR",
description="Statistical Quality Assessment of Dim. Red. Algorithms",
# long_description=readme(),
version=__version__,
license="BSD-3-Clause",
author="Eric Johnson",
author_email="[email protected]",
url="https://github.com/ejohnson643/EMBEDR",
project_urls={
"Source": "https://github.com/ejohnson643/EMBEDR",
"Issue Tracker": "https://github.com/ejohnson643/EMBEDR/issues",
},
packages=setuptools.find_packages(include=["EMBEDR", "EMBEDR.*"]),
python_requires=">=3.6",
install_requires=[
"numpy>=1.16.6",
"scikit-learn>=0.20",
"scipy",
"cython",
"numba",
"umap-learn"
],
extras_require={
"pynndescent": "pynndescent~=0.5.0",
},
ext_modules=extensions,
cmdclass={"build_ext": MyBuildExt},
)