-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathsetup.py
More file actions
480 lines (434 loc) · 18.4 KB
/
setup.py
File metadata and controls
480 lines (434 loc) · 18.4 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import glob
import os
import os.path
import platform
import subprocess
import sys
import sysconfig
from setuptools import Extension, find_namespace_packages, setup
from setuptools.command.build_ext import build_ext
from setuptools.errors import PlatformError
PY3 = sys.version > "3"
WIN32 = platform.system() == "Windows"
no_compiler = False # Flag for cases where we are sure there is no compiler exists in user's system
long_description = ""
previous_line = ""
with open("README.md") as dfile:
for line in dfile:
if (
not "image" in line
and not "target" in line
and not "DETAILED" in line
and not "**main**" in line
and not "**development" in line
and not "DETAILED" in previous_line
):
long_description += line
previous_line = line
# Parse options that now have to be passed as environment variables; current options
# GALPY_COMPILE_NO_OPENMP=1: compile without OpenMP support
# GALPY_COMPILE_COVERAGE=1: compile with gcov support
# GALPY_COMPILE_SINGLE_EXT=1: compile all of the C code into a single extension (just for testing, do not use this)
# GALPY_COMPILE_NO_EXT=1: do not compile any C extensions (just for testing, do not use this)
galpy_c_libraries = ["m", "gsl", "gslcblas", "gomp"]
if WIN32:
# On Windows it's unnecessary and erroneous to include m
galpy_c_libraries.remove("m")
# Windows does not need 'gomp' whether compiled with OpenMP or not
galpy_c_libraries.remove("gomp")
# Option to forego OpenMP
_NO_OPENMP = os.environ.get("GALPY_COMPILE_NO_OPENMP", "0") == "1"
if _NO_OPENMP or "PYODIDE" in os.environ:
extra_compile_args = ["-DNO_OMP"]
if not WIN32: # Because on Windows guaranteed to not have 'gomp' in the list
galpy_c_libraries.remove("gomp")
else:
extra_compile_args = ["-fopenmp" if not WIN32 else "/openmp"]
# Option to track coverage
if os.environ.get("GALPY_COMPILE_COVERAGE", "0") == "1":
extra_compile_args.extend(["-O0", "--coverage", "-D USING_COVERAGE"])
extra_link_args = ["--coverage"]
else:
extra_link_args = []
# Option to compile everything into a single extension
single_ext = os.environ.get("GALPY_COMPILE_SINGLE_EXT", "0") == "1"
# Option to not compile any extension
no_ext = os.environ.get("GALPY_COMPILE_NO_EXT", "0") == "1"
# code to check the GSL version; list cmd w/ shell=True only works on Windows
# (https://docs.python.org/3/library/subprocess.html#converting-argument-sequence)
cmd = ["gsl-config", "--version"]
try:
if sys.version_info < (2, 7): # subprocess.check_output does not exist
gsl_version = subprocess.Popen(
cmd, shell=sys.platform.startswith("win"), stdout=subprocess.PIPE
).communicate()[0]
else:
gsl_version = subprocess.check_output(cmd, shell=sys.platform.startswith("win"))
except (OSError, subprocess.CalledProcessError):
if "PYODIDE" in os.environ:
gsl_version = ["2", "7"]
else:
gsl_version = ["0", "0"]
else:
if PY3:
gsl_version = gsl_version.decode("utf-8")
gsl_version = gsl_version.split(".")
extra_compile_args.append("-D GSL_MAJOR_VERSION=%s" % (gsl_version[0]))
# Use gsl-config to get GSL include and library paths to ensure they can be
# found by the compiler and linker even if CFLAGS/LDFLAGS are not set;
# skip paths already present in CFLAGS/LDFLAGS (or INCLUDE/LIB on Windows) to avoid duplicates
gsl_include_dirs = []
gsl_library_dirs = []
if "PYODIDE" not in os.environ:
if WIN32:
_existing_includes = set(
filter(None, os.environ.get("INCLUDE", "").split(os.pathsep))
)
_existing_libdirs = set(
filter(None, os.environ.get("LIB", "").split(os.pathsep))
)
else:
_existing_includes = {
f[2:] for f in os.environ.get("CFLAGS", "").split() if f.startswith("-I")
}
_existing_libdirs = {
f[2:] for f in os.environ.get("LDFLAGS", "").split() if f.startswith("-L")
}
try:
# shell=True required on Windows to execute gsl-config.bat
# (https://docs.python.org/3/library/subprocess.html#converting-argument-sequence)
gsl_cflags = (
subprocess.check_output(
["gsl-config", "--cflags"], shell=sys.platform.startswith("win")
)
.decode("utf-8")
.strip()
)
for flag in gsl_cflags.split():
if flag.startswith("-I"):
path = flag[2:].strip('"')
# Verify the path actually contains GSL headers before using it
if path not in _existing_includes and os.path.isfile(
os.path.join(path, "gsl", "gsl_math.h")
):
gsl_include_dirs.append(path)
except (OSError, subprocess.CalledProcessError):
pass
try:
gsl_libs = (
subprocess.check_output(
["gsl-config", "--libs"], shell=sys.platform.startswith("win")
)
.decode("utf-8")
.strip()
)
for flag in gsl_libs.split():
if flag.startswith("-L"):
path = flag[2:].strip('"')
# Verify the path actually contains GSL libraries before using it
if path not in _existing_libdirs and (
glob.glob(os.path.join(path, "libgsl*"))
or os.path.isfile(os.path.join(path, "gsl.lib"))
):
gsl_library_dirs.append(path)
except (OSError, subprocess.CalledProcessError):
pass
# HACK for testing
# gsl_version= ['0','0']
# To properly export GSL symbols on Windows, need to defined GSL_DLL and WIN32
if WIN32:
extra_compile_args.append("-DGSL_DLL")
extra_compile_args.append("-DWIN32")
# main C extension
galpy_c_src = [
"galpy/util/bovy_symplecticode.c",
"galpy/util/bovy_rk.c",
"galpy/util/leung_dop853.c",
"galpy/util/bovy_coords.c",
"galpy/util/wez_ias15.c",
"galpy/util/wrap_xsf.cpp",
]
galpy_c_src.extend(glob.glob("galpy/potential/potential_c_ext/*.c"))
galpy_c_src.extend(glob.glob("galpy/potential/interppotential_c_ext/*.c"))
galpy_c_src.extend(glob.glob("galpy/util/interp_2d/*.c"))
galpy_c_src.extend(glob.glob("galpy/orbit/orbit_c_ext/*.c"))
galpy_c_src.extend(glob.glob("galpy/actionAngle/actionAngle_c_ext/*.c"))
galpy_c_include_dirs = [
"galpy/util",
"galpy/util/interp_2d",
"galpy/potential/potential_c_ext",
"galpy/potential/interppotential_c_ext",
"galpy/orbit/orbit_c_ext",
"galpy/actionAngle/actionAngle_c_ext",
"xsf/include",
]
galpy_c_include_dirs.extend(gsl_include_dirs)
# actionAngleTorus C extension (files here, so we can compile a single extension if so desidered)
actionAngleTorus_c_src = glob.glob("galpy/actionAngle/actionAngleTorus_c_ext/*.cc")
actionAngleTorus_c_src.extend(
glob.glob("galpy/actionAngle/actionAngleTorus_c_ext/torus/src/*.cc")
)
actionAngleTorus_c_src.extend(
[
"galpy/actionAngle/actionAngleTorus_c_ext/torus/src/utils/CHB.cc",
"galpy/actionAngle/actionAngleTorus_c_ext/torus/src/utils/Err.cc",
"galpy/actionAngle/actionAngleTorus_c_ext/torus/src/utils/Compress.cc",
"galpy/actionAngle/actionAngleTorus_c_ext/torus/src/utils/Numerics.cc",
"galpy/actionAngle/actionAngleTorus_c_ext/torus/src/utils/PJMNum.cc",
]
)
actionAngleTorus_c_src.extend(glob.glob("galpy/potential/potential_c_ext/*.c"))
actionAngleTorus_c_src.extend(glob.glob("galpy/orbit/orbit_c_ext/integrateFullOrbit.c"))
actionAngleTorus_c_src.extend(glob.glob("galpy/util/interp_2d/*.c"))
actionAngleTorus_c_src.extend(glob.glob("galpy/util/*.c"))
actionAngleTorus_c_src.append("galpy/util/wrap_xsf.cpp")
actionAngleTorus_include_dirs = [
"galpy/actionAngle/actionAngleTorus_c_ext",
"galpy/actionAngle/actionAngleTorus_c_ext/torus/src",
"galpy/actionAngle/actionAngleTorus_c_ext/torus/src/utils",
"galpy/actionAngle/actionAngle_c_ext",
"galpy/util/interp_2d",
"galpy/util",
"galpy/orbit/orbit_c_ext",
"galpy/potential/potential_c_ext",
"xsf/include",
]
actionAngleTorus_include_dirs.extend(gsl_include_dirs)
if single_ext: # add the code and libraries for the actionAngleTorus extensions
if os.path.exists("galpy/actionAngle/actionAngleTorus_c_ext/torus/src"):
galpy_c_src.extend(actionAngleTorus_c_src)
galpy_c_src = list(set(galpy_c_src))
galpy_c_include_dirs.extend(actionAngleTorus_include_dirs)
galpy_c_include_dirs = list(set(galpy_c_include_dirs))
# Installation of this extension using the GSL may (silently) fail, if the GSL
# is built for the wrong architecture, on Mac you can install the GSL correctly
# using
# brew install gsl --universal
galpy_c = Extension(
"libgalpy",
sources=galpy_c_src,
libraries=galpy_c_libraries,
include_dirs=galpy_c_include_dirs,
library_dirs=gsl_library_dirs,
runtime_library_dirs=[] if WIN32 else gsl_library_dirs,
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
)
ext_modules = []
if float(gsl_version[0]) >= 1.0 and (
float(gsl_version[0]) >= 2.0 or float(gsl_version[1]) >= 14.0
):
galpy_c_incl = True
ext_modules.append(galpy_c)
else:
galpy_c_incl = False
# Add the actionAngleTorus extension (src and include specified above)
actionAngleTorus_c = Extension(
"libgalpy_actionAngleTorus",
sources=actionAngleTorus_c_src,
libraries=galpy_c_libraries,
include_dirs=actionAngleTorus_include_dirs,
library_dirs=gsl_library_dirs,
runtime_library_dirs=[] if WIN32 else gsl_library_dirs,
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
)
if (
float(gsl_version[0]) >= 1.0
and (float(gsl_version[0]) >= 2.0 or float(gsl_version[1]) >= 14.0)
and os.path.exists("galpy/actionAngle/actionAngleTorus_c_ext/torus/src")
and not single_ext
):
actionAngleTorus_c_incl = True
ext_modules.append(actionAngleTorus_c)
else:
actionAngleTorus_c_incl = False
# Test whether compiler allows for the -fopenmp flag and all other flags
# to guard against compilation errors
# (https://stackoverflow.com/a/54518348)
def compiler_has_flag(compiler, flagname):
"""Test whether a given compiler supports a given option"""
import tempfile
from setuptools.errors import CompileError
with tempfile.NamedTemporaryFile("w", suffix=".cpp") as f:
f.write("int main (int argc, char **argv) { return 0; }")
try:
compiler.compile([f.name], extra_postargs=[flagname])
except CompileError:
return False
return True
# Test whether the compiler is clang, allowing for the fact that it's name might be gcc...
def compiler_is_clang(compiler):
# Test whether the compiler is clang by running the compiler with the --version flag and checking whether the output contains "clang"
try:
output = subprocess.check_output(
[compiler.compiler[0], "--version"], stderr=subprocess.STDOUT
)
except (OSError, subprocess.CalledProcessError):
return False
return b"clang" in output
# Now need to subclass BuildExt to access the compiler used and check flags
class BuildExt(build_ext):
def build_extensions(self):
ct = self.compiler.compiler_type
# Add C++17 standard for C++ files (required for xsf)
if WIN32:
# MSVC needs both /std:c++17 and /Zc:__cplusplus for proper C++17 support
cxx_flags = ["/std:c++17", "/Zc:__cplusplus"]
else:
cxx_flags = ["-std=c++17"]
compiler = self.compiler
# For Unix compilers (gcc/clang) - patch _compile()
if not WIN32 and hasattr(compiler, "_compile"):
old_compile = compiler._compile
def new_compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
# Add C++17 flag only for C++ files, but exclude torus files (not C++17 compatible)
if (
src.endswith((".cpp", ".cc", ".cxx"))
and "actionAngleTorus_c_ext" not in src
):
extra_postargs = list(extra_postargs or []) + cxx_flags
return old_compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
compiler._compile = new_compile
# For MSVC (Windows) - patch compile()
elif WIN32 and hasattr(compiler, "compile"):
old_msvc_compile = compiler.compile
def msvc_compile(
sources,
output_dir=None,
macros=None,
include_dirs=None,
debug=0,
extra_preargs=None,
extra_postargs=None,
depends=None,
):
new_postargs = list(extra_postargs or [])
# Check if any sources are C++ files that need C++17
for src in sources:
if (
src.endswith((".cpp", ".cc", ".cxx"))
and "actionAngleTorus_c_ext" not in src
):
new_postargs = list(extra_postargs or []) + cxx_flags
break
return old_msvc_compile(
sources,
output_dir,
macros,
include_dirs,
debug,
extra_preargs,
new_postargs,
depends,
)
compiler.compile = msvc_compile
if ct == "unix":
for ext in self.extensions:
# only add flags which pass the flag_filter
extra_compile_args = []
libraries = ext.libraries
for flag in set(ext.extra_compile_args):
if compiler_has_flag(self.compiler, flag):
extra_compile_args.append(flag)
elif compiler_is_clang(self.compiler) and flag == "-fopenmp":
# clang does not support -fopenmp, but does support -Xclang -fopenmp
extra_compile_args.append("-Xclang")
extra_compile_args.append("-fopenmp")
# Also adjust libraries as needed
if "gomp" in libraries:
libraries.remove("gomp")
if "omp" not in libraries:
libraries.append("omp")
elif flag == "-fopenmp" and "gomp" in libraries:
libraries.remove("gomp")
ext.extra_compile_args = extra_compile_args
ext.libraries = libraries
build_ext.build_extensions(self)
setup(
cmdclass=dict(build_ext=BuildExt), # this to allow compiler check above
name="galpy",
version="1.12.0.dev0",
description="Galactic Dynamics in python",
author="Jo Bovy",
author_email="[email protected]",
license="New BSD",
long_description=long_description,
long_description_content_type="text/markdown",
url="http://github.com/jobovy/galpy",
packages=find_namespace_packages(where=".", include=["galpy*"]),
package_data={
"galpy/orbit": ["named_objects.json"],
"galpy/df": ["data/*.sav"],
"": ["README.md", "README.dev", "LICENSE", "AUTHORS.rst"],
},
include_package_data=True,
python_requires=">=3.10",
install_requires=["packaging", "numpy>=1.7", "scipy", "matplotlib"],
extras_require={
"docs": ["sphinxext-opengraph", "sphinx-design", "markupsafe==2.0.1"]
},
ext_modules=ext_modules if not no_compiler and not no_ext else None,
classifiers=[
"Development Status :: 6 - Mature",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: C",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Environment :: WebAssembly :: Emscripten",
"Topic :: Scientific/Engineering :: Astronomy",
"Topic :: Scientific/Engineering :: Physics",
],
)
def print_gsl_message(num_messages=1):
if num_messages > 1:
this_str = "these installations"
else:
this_str = "this installation"
print(
'If you believe that %s should have worked, make sure\n(1) that the GSL include/ directory can be found by the compiler (you might have to edit CFLAGS for this: export CFLAGS="$CFLAGS -I/path/to/gsl/include/", or equivalent for C-type shells; replace /path/to/gsl/include/ with the actual path to the include directory),\n(2) that the GSL library can be found by the linker (you might have to edit LDFLAGS for this: export LDFLAGS="$LDFLAGS -L/path/to/gsl/lib/", or equivalent for C-type shells; replace /path/to/gsl/lib/ with the actual path to the lib directory),\n(3) and that `gsl-config --version` returns the correct version'
% this_str
)
num_gsl_warn = 0
if not galpy_c_incl:
num_gsl_warn += 1
print(
"\033[91;1m"
+ "WARNING: galpy C library not installed because your GSL version < 1.14"
+ "\033[0m"
)
if not actionAngleTorus_c_incl and not single_ext:
num_gsl_warn += 1
print(
"\033[91;1m"
+ "WARNING: galpy action-angle-torus C library not installed because your GSL version < 1.14 or because you did not first download the torus code as explained in the installation guide in the html documentation"
+ "\033[0m"
)
if num_gsl_warn > 0:
print_gsl_message(num_messages=num_gsl_warn)
print(
"\033[1m"
+ "These warning messages about the C code do not mean that the python package was not installed successfully"
+ "\033[0m"
)
print("\033[1m" + "Finished installing galpy" + "\033[0m")
print(
"You can run the test suite using `pytest -v tests/` to check the installation (but note that the test suite currently takes about 50 minutes to run)"
)
# if single_ext, symlink the other (non-compiled) extensions to libgalpy.so (use EXT_SUFFIX for python3 compatibility)
if PY3:
_ext_suffix = sysconfig.get_config_var("EXT_SUFFIX")
else:
_ext_suffix = ".so"
if single_ext:
if not os.path.exists(
"libgalpy_actionAngleTorus%s" % _ext_suffix
) and os.path.exists("galpy/actionAngle/actionAngleTorus_c_ext/torus/src"):
os.symlink(
"libgalpy%s" % _ext_suffix, "libgalpy_actionAngleTorus%s" % _ext_suffix
)