forked from phonopy/phono3py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.py
More file actions
333 lines (289 loc) · 9.99 KB
/
setup.py
File metadata and controls
333 lines (289 loc) · 9.99 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
"""Phono3py setup.py.
Cmake handles automatic finding of library.
Custom settings should be written in site.cfg.
To fully customize using site.cfg,
set PHONO3PY_USE_CMAKE=false to avoid running cmake.
"""
import os
import pathlib
import shutil
import subprocess
import numpy
import setuptools
if (
"PHONO3PY_USE_CMAKE" in os.environ
and os.environ["PHONO3PY_USE_CMAKE"].lower() == "false"
):
use_cmake = False
else:
use_cmake = True
def _run_cmake(build_dir):
build_dir.mkdir()
args = [
"cmake",
"-S",
".",
"-B",
"_build",
"-DPHONONCALC=on",
"-DPHONO3PY=on",
"-DCMAKE_INSTALL_PREFIX=.",
]
# if "CONDA_PREFIX" in os.environ:
# args.append("-DUSE_CONDA_PATH=on")
# if "CC" in os.environ:
# args.append(f'-DCMAKE_C_COMPILER={os.environ["CC"]}')
cmake_output = subprocess.check_output(args)
print(cmake_output.decode("utf-8"))
subprocess.check_call(["cmake", "--build", "_build", "-v"])
return cmake_output
def _clean_cmake(build_dir):
if build_dir.exists():
shutil.rmtree(build_dir)
def _get_params_from_site_cfg():
"""Read extra_compile_args and extra_link_args.
Examples
--------
# For macOS
extra_compile_args = -fopenmp=libomp
extra_link_args = -lomp -lopenblas
# For linux
extra_compile_args = -fopenmp
extra_link_args = -lgomp -lopenblas -lpthread
"""
params = {
"define_macros": [],
"extra_link_args": [],
"extra_compile_args": [],
"extra_objects": [],
"include_dirs": [],
}
use_mkl_lapacke = False
use_threaded_blas = False
site_cfg_file = pathlib.Path.cwd() / "site.cfg"
if not site_cfg_file.exists():
return params
with open(site_cfg_file) as f:
lines = [line.strip().split("=", maxsplit=1) for line in f]
for line in lines:
if len(line) < 2:
continue
key = line[0].strip()
val = line[1].strip()
if key not in params:
continue
if key == "define_macros":
pair = val.split(maxsplit=1)
if pair[1].lower() == "none":
pair[1] = None
params[key].append(tuple(pair))
else:
if "mkl" in val:
use_mkl_lapacke = True
if "openblas" in val:
use_threaded_blas = True
params[key] += val.split()
if use_mkl_lapacke:
params["define_macros"].append(("MKL_LAPACKE", None))
if use_threaded_blas:
params["define_macros"].append(("MULTITHREADED_BLAS", None))
if "THM_EPSILON" not in [macro[0] for macro in params["define_macros"]]:
params["define_macros"].append(("THM_EPSILON", "1e-10"))
print("=============================================")
print("Parameters found in site.cfg")
for key, val in params.items():
print(f"{key}: {val}")
print("=============================================")
return params
def _get_extensions(build_dir):
"""Return python extension setting.
User customization by site.cfg file
-----------------------------------
See _get_params_from_site_cfg().
Automatic search using cmake
----------------------------
Invoked by environment variable unless PHONO3PY_USE_CMAKE=false.
"""
params = _get_params_from_site_cfg()
extra_objects_ph3py = []
extra_objects_phcalc = []
if not use_cmake or not shutil.which("cmake"):
print("** Setup without using cmake **")
sources_ph3py = [
"c/_phono3py.c",
"c/bzgrid.c",
"c/collision_matrix.c",
"c/fc3.c",
"c/grgrid.c",
"c/imag_self_energy_with_g.c",
"c/interaction.c",
"c/isotope.c",
"c/lagrid.c",
"c/lapack_wrapper.c",
"c/phono3py.c",
"c/phonoc_utils.c",
"c/pp_collision.c",
"c/real_self_energy.c",
"c/real_to_reciprocal.c",
"c/reciprocal_to_normal.c",
"c/snf3x3.c",
"c/tetrahedron_method.c",
"c/triplet.c",
"c/triplet_grid.c",
"c/triplet_iw.c",
]
sources_phcalc = [
"c/_phononcalc.c",
"c/dynmat.c",
"c/lapack_wrapper.c",
"c/phonon.c",
"c/phononcalc.c",
]
else:
print("** Setup using cmake **")
use_mkl_lapacke = False
found_extra_link_args = []
found_extra_compile_args = []
sources_ph3py = ["c/_phono3py.c"]
sources_phcalc = ["c/_phononcalc.c"]
cmake_output = _run_cmake(build_dir)
found_flags = {}
found_libs = {}
for line in cmake_output.decode("utf-8").split("\n"):
for key in ["BLAS", "LAPACK", "OpenMP"]:
if f"{key} libs" in line and len(line.split()) > 3:
found_libs[key] = line.split()[3].split(";")
if f"{key} flags" in line and len(line.split()) > 3:
found_flags[key] = line.split()[3].split(";")
for key, value in found_libs.items():
found_extra_link_args += value
for element in value:
if "libmkl" in element:
use_mkl_lapacke = True
for key, value in found_flags.items():
found_extra_compile_args += value
if use_mkl_lapacke:
params["define_macros"].append(("MKL_LAPACKE", None))
libph3py = list((pathlib.Path.cwd() / "_build").glob("*ph3py.*"))
if libph3py:
print("=============================================")
print(f"Phono3py library: {libph3py[0]}")
print("=============================================")
extra_objects_ph3py += [str(libph3py[0])]
libphcalc = list((pathlib.Path.cwd() / "_build").glob("*phcalc.*"))
if libphcalc:
print("=============================================")
print(f"Phonon library: {libphcalc[0]}")
print("=============================================")
extra_objects_phcalc += [str(libphcalc[0])]
params["extra_link_args"] += found_extra_link_args
params["extra_compile_args"] += found_extra_compile_args
print("=============================================")
print("Parameters found by cmake")
print("extra_compile_args: ", found_extra_compile_args)
print("extra_link_args: ", found_extra_link_args)
print("define_macros: ", params["define_macros"])
print("=============================================")
print()
extensions = []
params["define_macros"].append(("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION"))
params["include_dirs"] += ["c", numpy.get_include()]
extensions.append(
setuptools.Extension(
"phono3py._phono3py",
sources=sources_ph3py,
extra_link_args=params["extra_link_args"],
include_dirs=params["include_dirs"],
extra_compile_args=params["extra_compile_args"],
extra_objects=params["extra_objects"] + extra_objects_ph3py,
define_macros=params["define_macros"],
)
)
extensions.append(
setuptools.Extension(
"phono3py._phononcalc",
sources=sources_phcalc,
extra_link_args=params["extra_link_args"],
include_dirs=params["include_dirs"],
extra_compile_args=params["extra_compile_args"],
extra_objects=params["extra_objects"] + extra_objects_phcalc,
define_macros=params["define_macros"],
)
)
return extensions
def _get_version() -> str:
git_num = None
version_nums = [None, None, None]
with open("phono3py/version.py") as w:
for line in w:
if "__version__" in line:
for i, num in enumerate(line.split()[2].strip('"').split(".")):
version_nums[i] = num
break
# To deploy to pypi by travis-CI
if os.path.isfile("__nanoversion__.txt"):
nanoversion = 0
with open("__nanoversion__.txt") as nv:
try:
for line in nv:
nanoversion = int(line.strip())
break
except ValueError:
nanoversion = 0
if nanoversion != 0:
version_nums.append(nanoversion)
elif git_num:
version_nums.append(git_num)
if None in version_nums:
print("Failed to get version number in setup.py.")
raise
version = ".".join(["%s" % n for n in version_nums[:3]])
if len(version_nums) > 3:
version += "-%s" % version_nums[3]
return version
def main(build_dir):
"""Run setuptools."""
version = _get_version()
packages_phono3py = [
"phono3py",
"phono3py.conductivity",
"phono3py.cui",
"phono3py.interface",
"phono3py.other",
"phono3py.phonon",
"phono3py.phonon3",
"phono3py.sscha",
]
scripts_phono3py = [
"scripts/phono3py",
"scripts/phono3py-load",
"scripts/phono3py-kaccum",
"scripts/phono3py-kdeplot",
"scripts/phono3py-coleigplot",
]
setuptools.setup(
name="phono3py",
version=version,
description="This is the phono3py module.",
author="Atsushi Togo",
author_email="atz.togo@gmail.com",
url="http://phonopy.github.io/phono3py/",
packages=packages_phono3py,
python_requires=">=3.7",
install_requires=[
"numpy>=1.15.0",
"scipy",
"PyYAML",
"matplotlib>=2.2.2",
"h5py",
"spglib",
"phonopy>=2.18,<2.20",
],
provides=["phono3py"],
scripts=scripts_phono3py,
ext_modules=_get_extensions(build_dir),
)
_clean_cmake(build_dir)
if __name__ == "__main__":
build_dir = pathlib.Path.cwd() / "_build"
main(build_dir)