-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathprepare_build.py
258 lines (224 loc) · 9.28 KB
/
prepare_build.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
# pylint: disable=import-outside-toplevel
"""Execute this file before building source or binary distributions."""
import copy
import importlib
import inspect
import os
import sys
from typing import get_type_hints, Literal
import click
import Cython.Build
import numpy
import setuptools
INT = "numpy.int64_t"
def _clear_autogendir() -> None:
dirpath = os.path.join("hydpy", "cythons", "autogen")
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
if os.path.isfile(filepath) and (filename != "__init__.py"):
os.remove(filepath)
def _prepare_cythonoptions(fast_cython: bool, profile_cython: bool) -> list[str]:
# ToDo: do not share code with PyxWriter.cythondistutilsoptions
cythonoptions = [
"# !python",
"# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION",
"# cython: language_level=3",
"# cython: cpow=True",
]
if fast_cython:
cythonoptions.extend(
[
"# cython: boundscheck=False",
"# cython: wraparound=False",
"# cython: initializedcheck=False",
"# cython: cdivision=True",
]
)
else:
cythonoptions.extend(
[
"# cython: boundscheck=True",
"# cython: wraparound=True",
"# cython: initializedcheck=True",
"# cython: cdivision=False",
]
)
if profile_cython:
cythonoptions.extend(
[
"# cython: linetrace=True",
"# distutils: define_macros=CYTHON_TRACE=1",
"# distutils: define_macros=CYTHON_TRACE_NOGIL=1",
]
)
return cythonoptions
def _prepare_baseextensions(fast_cython: bool, profile_cython: bool) -> None:
names = []
for name in sorted(os.listdir(os.path.join("hydpy", "cythons"))):
if name.split(".")[-1] == "pyx":
names.append(name.split(".")[0])
opt = _prepare_cythonoptions(fast_cython=fast_cython, profile_cython=profile_cython)
for name in names:
for suffix in ("pyx", "pxd"):
filename = f"{name}.{suffix}"
path_in = os.path.join("hydpy", "cythons", filename)
path_out = os.path.join("hydpy", "cythons", "autogen", filename)
with open(path_in, encoding="utf-8") as file_in:
text = file_in.read()
text = text.replace(" int ", " " + INT + " ")
text = text.replace(" int[", " " + INT + "[")
with open(path_out, "w", encoding="utf-8") as file_out:
file_out.write("\n".join(opt) + "\n\n")
file_out.write(text)
def _convert_interfaces(fast_cython: bool, profile_cython: bool) -> None:
from hydpy import config
from hydpy.core.modeltools import abstractmodelmethods
from hydpy.cythons.modelutils import TYPE2STR
_nogil = " noexcept nogil" if config.FASTCYTHON else ""
def _write_twice(text: str) -> None:
pxdfile.write(text)
pyxfile.write(text)
opt = _prepare_cythonoptions(fast_cython=fast_cython, profile_cython=profile_cython)
pydirpath = os.path.join("hydpy", "interfaces")
cydirpath = os.path.join("hydpy", "cythons", "autogen")
pyfilenames = (n for n in os.listdir(pydirpath) if n.endswith(".py"))
modulenames = (n[:-3] for n in pyfilenames if n != "__init__.py")
pxdpath = os.path.join(cydirpath, f"masterinterface.pxd")
pyxpath = os.path.join(cydirpath, f"masterinterface.pyx")
funcname2signature: dict[str, str] = {}
with open(pxdpath, "w", encoding="utf-8") as pxdfile, open(
pyxpath, "w", encoding="utf-8"
) as pyxfile:
_write_twice("\n".join(opt) + "\n")
_write_twice("\ncimport numpy\n")
_write_twice("\nfrom hydpy.cythons.autogen cimport interfaceutils\n")
_write_twice("\n\ncdef class MasterInterface(interfaceutils.BaseInterface):\n")
signature = f"\n cdef void new2old(self) {_nogil}"
pxdfile.write(f"{signature}\n")
pyxfile.write(f"{signature}:\n")
pyxfile.write(f" pass\n")
for modulename in modulenames:
pymodule = importlib.import_module(f"hydpy.interfaces.{modulename}")
name2class = {
name: member
for name, member in inspect.getmembers(pymodule)
if (inspect.isclass(member) and (inspect.getmodule(member) is pymodule))
}
for classname, class_ in name2class.items():
name2func = {
n: m
for n, m in inspect.getmembers(class_)
if inspect.isfunction(m) and (m in abstractmodelmethods)
}
for funcname, func in name2func.items():
typehints = get_type_hints(func)
name2type = {n: TYPE2STR[t] for n, t in typehints.items()}
args = ", ".join(
f"{t} {n}" for n, t in name2type.items() if n != "return"
)
returntype = name2type["return"]
signature = (
f"\n cdef {returntype} {funcname}(self, {args}) {_nogil}"
)
if funcname in funcname2signature:
assert signature == funcname2signature[funcname]
else:
funcname2signature[funcname] = signature
pxdfile.write(f"{signature}\n")
pyxfile.write(f"{signature}:\n")
if typehints["return"] is type(None):
pyxfile.write(" pass\n")
elif typehints["return"] is float:
pyxfile.write(" return 0.0\n")
elif typehints["return"] is int:
pyxfile.write(" return 0\n")
else:
assert False
def _compile_extensions(filetype: Literal["utils", "interfaces"]) -> None:
argv = copy.deepcopy(sys.argv)
try:
sys.argv = [sys.argv[0], "build_ext", "--build-lib=.", "--build-temp=."]
extension = setuptools.Extension(
"*",
[f"hydpy/cythons/autogen/*{filetype}.pyx"],
include_dirs=[numpy.get_include()],
)
setuptools.setup(
name="temporary", ext_modules=Cython.Build.cythonize([extension])
)
finally:
sys.argv = argv
def _prepare_modelspecifics(fast_cython: bool, profile_cython: bool) -> None:
from hydpy import config
from hydpy import pub
from hydpy import models
from hydpy.core import aliastools
from hydpy.cythons import modelutils
from hydpy.exe import xmltools
config.FASTCYTHON = fast_cython
config.PROFILECYTHON = profile_cython
with pub.options.usecython(False):
path_: str = models.__path__[0]
for name in [fn.split(".")[0] for fn in sorted(os.listdir(path_))]:
if not name.startswith("_"):
module = importlib.import_module(f"hydpy.models.{name}")
cythonizer: modelutils.Cythonizer | None
cythonizer = getattr(module, "cythonizer", None)
if cythonizer:
cythonizer.pyxwriter.write()
aliastools.write_sequencealiases()
xmltools.XSDWriter().write_xsd()
@click.command()
@click.option(
"-f",
"--fast-cython",
type=bool,
default=True,
help="See the documentation on option `FASTCYTHON` option of module `config`.",
)
@click.option(
"-p",
"--profile-cython",
type=bool,
default=False,
help="See the documentation on option `PROFILECYTHON` option of module `config`.",
)
@click.option(
"-e",
"--compile-baseextensions",
type=bool,
default=True,
help="Translate the modified Cython extension files into C files and compile them.",
)
@click.option(
"-i",
"--compile-interfaceextensions",
type=bool,
default=False,
help="Translate the generate Cython interface files into C files and compile them.",
)
def main(
fast_cython: bool,
profile_cython: bool,
compile_baseextensions: bool,
compile_interfaceextensions: bool,
) -> None:
"""Perform the following tasks:
Copy the Cython source code of the extension modules from package `cythons` to
subpackage `autogen` and modify the source code where necessary. Then, optionally,
compile the modified extensions.
Create the Cython source code of all interface-specific extension modules defined
in the `interfaces` subpackage. Then, optionally, compile the created extensions.
Create the Cython source code of all model-specific extension modules.
Write additional XML configuration files and sequence alias files.
"""
_clear_autogendir()
_prepare_baseextensions(fast_cython=fast_cython, profile_cython=profile_cython)
if compile_baseextensions:
_compile_extensions(filetype="utils")
_convert_interfaces(fast_cython=fast_cython, profile_cython=profile_cython)
if compile_interfaceextensions:
_compile_extensions(filetype="interface")
_prepare_modelspecifics(fast_cython=fast_cython, profile_cython=profile_cython)
if __name__ == "__main__":
main() # pylint: disable=no-value-for-parameter