forked from theochem/cgbasis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
executable file
·267 lines (226 loc) · 9.44 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
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import glob
import json
import subprocess
import Cython.Build
import numpy as np
from setuptools import setup
from distutils.extension import Extension
# Try to get the version from git describe
__version__ = "0.1.0"
try:
print("Trying to get the version from git describe")
git_describe = subprocess.check_output(["git", "describe", "--tags"])
version_words = git_describe.decode("utf-8").strip().split("-")
__version__ = version_words[0]
if len(version_words) > 1:
__version__ += ".post" + version_words[1]
print("Version from git describe: {}".format(__version__))
except (subprocess.CalledProcessError, OSError):
pass
# Interact with version.py
fn_version = os.path.join(os.path.dirname(__file__), "gbasis", "version.py")
version_template = """
# Do not edit this file, versioning is governed by ``git describe --tags`` and ``setup.py``.
__version__ = "{}"
"""
if __version__ is None:
print("Trying to get the version from {}", format(fn_version))
# Try to load the git version tag from version.py
try:
with open(fn_version, "r") as fh:
__version__ = fh.read().split("=")[-1].replace("\"", "").strip()
except IOError:
print("Could not determine version. Giving up.")
sys.exit(1)
print("Version according to {}: {}".format(fn_version, __version__))
else:
# Store the git version tag in version.py
print("Writing version to {}".format(fn_version))
with open(fn_version, "w") as fh:
fh.write(version_template.format(__version__))
# Library configuration functions
# -------------------------------
lib_config_keys = ["include_dirs", "library_dirs", "libraries", "extra_objects",
"extra_compile_args", "extra_link_args"]
def print_lib_config(heading, lib_config):
"""Print (partial) lib_config"""
print(" %s" % heading)
if len(lib_config) == 0:
print(" -")
else:
for key, value in sorted(lib_config.items()):
if len(value) > 0:
print(" %s: %s" % (key, value))
def get_lib_config_setup(prefix, fn_setup_cfg):
"""Get library configuration from a setup.cfg"""
lib_config = {}
if os.path.isfile(fn_setup_cfg):
config = ConfigParser.ConfigParser()
config.read(fn_setup_cfg)
if config.has_section(prefix):
for key in lib_config_keys:
if config.has_option(prefix, key):
value = config.get(prefix, key).strip()
if value is not None and len(value) > 0:
lib_config[key] = value.split(":")
print_lib_config("From %s" % fn_setup_cfg, lib_config)
else:
print(" File %s not found. Skipping." % fn_setup_cfg)
return lib_config
def get_lib_config_env(prefix):
"""Read library config from the environment variables"""
lib_config = {}
for key in lib_config_keys:
varname = ("%s_%s" % (prefix, key)).upper()
value = os.getenv(varname)
if value is not None:
lib_config[key] = value.split(":")
print_lib_config("From environment variables", lib_config)
return lib_config
class PkgConfigError(Exception):
pass
def run_pkg_config(libname, option):
"""Safely try to call pkg-config"""
try:
return subprocess.check_output(["pkg-config", libname, "--" + option],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
raise PkgConfigError("pkg-config did not exit properly")
except OSError:
raise PkgConfigError("pkg-config not installed")
def get_lib_config_pkg(libname):
"""Get library config from the pkg-config program"""
lib_config = {
"include_dirs": [word[2:] for word in run_pkg_config(libname, "cflags-only-I").split()],
"library_dirs": [word[2:] for word in run_pkg_config(libname, "libs-only-L").split()],
"libraries": [word[2:] for word in run_pkg_config(libname, "libs-only-l").split()],
"extra_compile_args": run_pkg_config(libname, "cflags-only-other").split(),
"extra_link_args": run_pkg_config(libname, "libs-only-other").split(),
}
print_lib_config("From pkg-config", lib_config)
return lib_config
def all_empty(lib_config):
"""Test if all lib_config fields are empty"""
if len(lib_config) == 0:
return True
return all(len(value) == 0 for value in lib_config.values())
def all_exist(lib_config):
"""Test if all paths in the lib_config exist"""
for key, value in lib_config.items():
for path in value:
if not os.path.exists(path):
return False
return True
def lib_config_magic(prefix, libname, static_config={}, known_include_dirs=[]):
"""Detect the configuration of a given library
Parameters
----------
prefix : str
The prefix for this library. This is a name that HORTON uses to refer to the
library.
libname : str
The library name as it is known to the compiler and to pkg-config. For example, if
the shared object is libfoo.so, then the library name is foo.
static_config : dict
If given, this static library configuration is attempted. Ignored when empty, or
when it contains non-existing files.
known_include_dirs : list of str
When all other methods of finding the library settings fail, the first existing
directory in this list is added to the include path. This is useful when header
files are commonly installed in a place that is not considered by default by most
compilers.
"""
print("%s Configuration" % prefix.upper())
# Start out empty
lib_config = dict((key, []) for key in lib_config_keys)
# Update with info from setup.cfg
lib_config.update(get_lib_config_setup(prefix, "setup.cfg"))
# Override with environment variables
lib_config.update(get_lib_config_env(prefix))
# If no environment variables were set, attempt to use the static config.
if all_empty(lib_config):
if all_empty(static_config):
print(" No static config available for this library")
elif not all_exist(static_config):
print_lib_config("Static lib not found in ${QAWORKDIR}", static_config)
else:
# If the static build is present, use it.
print_lib_config("Static lib config in ${QAWORKDIR}", static_config)
lib_config.update(static_config)
# If also the static config did not work, try pkg-config
if all_empty(lib_config):
try:
# Try to get dynamic link info from pkg-config
lib_config.update(get_lib_config_pkg(libname))
except PkgConfigError:
print(" pkg-config failed.")
# Uber-dumb fallback. It works most of the times.
if all_empty(lib_config):
lib_config["libraries"] = [libname]
for include_dir in known_include_dirs:
if os.path.isdir(include_dir):
lib_config["include_dirs"] = [include_dir]
break
print_lib_config("Last resort fallback plan", lib_config)
print_lib_config("Final", lib_config)
return lib_config
# Locate ${QAWORKDIR}
# -------------------
qaworkdir = "tools/libs"
# Configuration of LibInt2
# ------------------------
# Load dependency information
with open("dependencies.json") as f:
dependencies = json.load(f)
dependencies = dict((d['name'], d) for d in dependencies)
# Static build info in the QAWORKDIR:
libint2_dir = "%s/cached/libint-%s" % (qaworkdir, str(dependencies["libint"]["version_ci"]))
libint2_static_config = {
"extra_objects": ["%s/lib/libint2.a" % libint2_dir],
"include_dirs": ["%s/include/libint2" % libint2_dir],
}
# Common include dirs that are not considered by the compiler by default:
known_libint2_include_dirs = ["/usr/include/libint2", "/opt/local/include/libint2"]
libint2_config = lib_config_magic(
"libint2", "int2", libint2_static_config, known_libint2_include_dirs)
setup(
name="gbasis",
version=__version__,
description="",
author="Toon Verstraelen",
author_email="[email protected]",
url="https://github.com/theochem/gbasis",
package_dir={"gbasis": "gbasis"},
packages=["gbasis", "gbasis.test"],
cmdclass={"build_ext": Cython.Build.build_ext},
ext_modules=[Extension(
"gbasis.cext",
sources=["gbasis/cext.pyx"] + glob.glob("gbasis/*.cpp"),
depends=glob.glob("gbasis/*.h") + glob.glob("gbasis/*.h"),
include_dirs=[np.get_include(), "."] +
libint2_config["include_dirs"],
library_dirs=libint2_config["library_dirs"],
libraries=libint2_config["libraries"],
extra_objects=libint2_config["extra_objects"],
extra_compile_args=libint2_config["extra_compile_args"] +
["-std=c++11"],
extra_link_args=libint2_config["extra_link_args"],
language="c++"),
],
include_package_data=True,
classifiers=[
"Environment :: Console",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Topic :: Scientific/Engineering :: Physics",
"Topic :: Scientific/Engineering :: Chemistry",
"Intended Audience :: Science/Research",
],
requires=["numpy", "scipy", "setuptools", "distutils", "Cython"],
)