forked from wannesm/dtaidistance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.py
executable file
·323 lines (280 loc) · 10.2 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
python3 setup.py build_ext --inplace
"""
from setuptools import setup, Command
from setuptools.extension import Extension
from setuptools.command.test import test as TestCommand
from setuptools.command.sdist import sdist as SDistCommand
from setuptools.command.build_ext import build_ext as BuildExtCommand
from setuptools.command.install import install
from setuptools import Distribution
import platform
import os
import sys
import re
import subprocess as sp
try:
import numpy
np_include_dirs = [numpy.get_include()]
except ImportError:
numpy = None
np_include_dirs = []
try:
from Cython.Build import cythonize
except ImportError:
cythonize = None
here = os.path.abspath(os.path.dirname(__file__))
c_args = {
'unix': ['-fopenmp'],
'msvc': ['/openmp', '/Ox', '/fp:fast', '/favor:INTEL64', '/Og'],
'mingw32': ['-fopenmp', '-O3', '-ffast-math', '-march=native']
}
l_args = {
'unix': ['-fopenmp'],
'msvc': [],
'mingw32': ['-fopenmp']
}
class MySDistCommand(SDistCommand):
def run(self):
PrepReadme.run_pandoc()
super().run()
class PrepReadme(Command):
description = "Translate readme from Markdown to ReStructuredText"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
PrepReadme.run_pandoc()
@staticmethod
def run_pandoc():
import subprocess as sp
print("running pandoc")
try:
sp.call(['pandoc', '--from=markdown', '--to=rst', '--output=README', 'README.md'])
except sp.CalledProcessError as err:
print("Pandoc failed, Markdown format will be used.")
print(err)
class PyTest(TestCommand):
description = "Run tests"
user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]
pytest_args = []
test_args = []
def initialize_options(self):
self.pytest_args = ['--ignore=venv']
try:
import pytest_benchmark
self.pytest_args += ['--benchmark-skip']
except ImportError:
print("No benchmark library, ignore benchmarks")
self.pytest_args += ['--ignore', 'tests/test_benchmark.py']
def finalize_options(self):
pass
def run_tests(self):
import pytest
sys.path.append('.')
errno = pytest.main(self.pytest_args)
sys.exit(errno)
class MyDistribution(Distribution):
global_options = Distribution.global_options + [
('noopenmp', None, 'Disable compilation with openmp')
]
def __init__(self, attrs=None):
self.noopenmp = 0
super().__init__(attrs)
class MyInstallCommand(install):
pass
# def initialize_options(self):
# install.initialize_options(self)
# def finalize_options(self):
# install.finalize_options(self)
# def run(self):
# install.run(self)
def set_custom_envvars_for_homebrew():
"""Update environment variables automatically for Homebrew if CC is not set"""
if platform.system() == 'Darwin' and "CC" not in os.environ:
print("Set custom environment variables for Homebrew Clang because CC is not set")
cppflags = []
if "CPPFLAGS" in os.environ:
cppflags.append(os.environ["CPPFLAGS"])
cflags = []
if "CFLAGS" in os.environ:
cflags.append(os.environ["CFLAGS"])
ldflags = []
if "LDFLAGS" in os.environ:
ldflags.append(os.environ["LDFLAGS"])
if os.path.exists("/usr/local/opt/llvm/bin/clang"):
# We have a recent version of LLVM that probably supports openmp to compile parallel C code (installed using
# `brew install llvm`).
os.environ["CC"] = "/usr/local/opt/llvm/bin/clang"
print("CC={}".format(os.environ["CC"]))
ldflags += ["-L/usr/local/opt/llvm/lib"]
cppflags += ["-I/usr/local/opt/llvm/include"]
cflags += ["-I/usr/local/opt/llvm/include"]
try:
mac_ver = [int(nb) for nb in platform.mac_ver()[0].split(".")]
if mac_ver[0] == 10 and mac_ver[1] >= 14:
# From Mojave on, the header files are part of Xcode.app
incpath = '-I/Applications/Xcode.app/Contents/Developer/Platforms/' + \
'MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include'
cppflags += [incpath]
cflags += [incpath]
except Exception as exc:
print("Failed to check version")
print(exc)
if len(cppflags) > 0:
os.environ["CPPFLAGS"] = " ".join(cppflags)
print("CPPFLAGS={}".format(os.environ["CPPFLAGS"]))
if len(cflags) > 0:
os.environ["CFLAGS"] = " ".join(cflags)
print("CFLAGS={}".format(os.environ["CFLAGS"]))
if len(ldflags) > 0:
os.environ["LDFLAGS"] = " ".join(ldflags)
print("LDFLAGS={}".format(os.environ["LDFLAGS"]))
else:
print("Using the following environment variables:")
print("CC={}".format(os.environ.get("CC", "")))
print("CPPFLAGS={}".format(os.environ.get("CPPFLAGS", "")))
print("CFLAGS={}".format(os.environ.get("CPLAGS", "")))
print("LDFLAGS={}".format(os.environ.get("LDFLAGS", "")))
class MyBuildExtCommand(BuildExtCommand):
def build_extensions(self):
c = self.compiler.compiler_type
print("Compiler type: {}".format(c))
print("--noopenmp: {}".format(self.distribution.noopenmp))
if self.distribution.noopenmp == 0 and not check_openmp(self.compiler.compiler[0]):
print("WARNING: OpenMP is not available, disabling OpenMP (no parallel computing in C)")
self.distribution.noopenmp = 1
if c in c_args:
if self.distribution.noopenmp == 1:
args = [arg for arg in c_args[c] if "openmp" not in arg]
else:
args = c_args[c]
for e in self.extensions:
e.extra_compile_args = args
else:
print("Unknown compiler type: {}".format(c))
if c in l_args:
if self.distribution.noopenmp == 1:
args = [arg for arg in l_args[c] if "openmp" not in arg]
else:
args = l_args[c]
for e in self.extensions:
e.extra_link_args = args
BuildExtCommand.build_extensions(self)
def initialize_options(self):
set_custom_envvars_for_homebrew()
super().initialize_options()
# def finalize_options(self):
# super().finalize_options()
# def run(self):
# super().run()
class MyBuildExtInPlaceCommand(MyBuildExtCommand):
def initialize_options(self):
super().initialize_options()
self.inplace = True
def check_openmp(cc_bin):
"""Check if OpenMP is available"""
print("Checking for OpenMP availability")
cc_binname = os.path.basename(cc_bin)
args = None
kwargs = None
if "clang" in cc_binname or "cc" in cc_binname:
args = [[str(cc_bin), "-dM", "-E", "-fopenmp", "-"]]
kwargs = {"stdout": sp.PIPE, "input": '', "encoding": 'ascii'}
print(" ".join(args[0]) + " ".join(str(k) + "=" + str(v) for k, v in kwargs.items()))
if args is not None:
try:
p = sp.run(*args, **kwargs)
defs = p.stdout.splitlines()
for curdef in defs:
if "_OPENMP" in curdef:
print("... found OpenMP")
return True
except Exception:
print("... no OpenMP")
return False
else:
print("... do not know how to check for OpenMP (unknown CC)")
return True
return False
# Set up extension
if cythonize is not None and numpy is not None:
print("create ext modules")
ext_modules = cythonize([
Extension(
"dtaidistance.dtw_c", ["dtaidistance/dtw_c.pyx"],
include_dirs=np_include_dirs,
extra_compile_args=[],
extra_link_args=[])])
elif numpy is None:
print("WARNING: Numpy was not found, preparing a pure Python version.")
ext_modules = []
else:
print("WARNING: Cython was not found, preparing a pure Python version.")
ext_modules = []
install_requires = ['numpy', 'cython']
tests_require = ['pytest', 'matplotlib']
# Check version number
with open('dtaidistance/__init__.py', 'r', encoding='utf-8') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
# Set up readme file
readme_path = os.path.join(here, 'README')
if not os.path.exists(readme_path):
try:
PrepReadme.run_pandoc()
except Exception:
pass
if os.path.exists(readme_path):
with open(readme_path, 'r', encoding='utf-8') as f:
long_description = f.read()
else:
with open(os.path.join(here, 'README.md'), 'r', encoding='utf-8') as f:
long_description = f.read()
# Create setup
setup(
name='dtaidistance',
version=version,
description='Distance measures for time series',
long_description=long_description,
author='Wannes Meert',
author_email='[email protected]',
url='https://dtai.cs.kuleuven.be',
project_urls={
'DTAIDistance documentation': 'http://dtaidistance.readthedocs.io/en/latest/',
'DTAIDistance source': 'https://github.com/wannesm/dtaidistance'
},
packages=["dtaidistance"],
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'vis': ['matplotlib']
},
include_package_data=True,
package_data={
'': ['*.pyx', '*.pxd'],
},
distclass=MyDistribution,
cmdclass={
'test': PyTest,
'readme': PrepReadme,
'sdist': MySDistCommand,
'buildinplace': MyBuildExtInPlaceCommand,
'build_ext': MyBuildExtCommand,
'install': MyInstallCommand
},
license='Apache 2.0',
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3'
],
keywords='dtw',
ext_modules=ext_modules
)