forked from statsmodels/statsmodels
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
416 lines (357 loc) · 13.5 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
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
"""
To build with coverage of Cython files
export SM_CYTHON_COVERAGE=1
python -m pip install -e .
pytest --cov=statsmodels statsmodels
coverage html
"""
from setuptools import Command, Extension, find_packages, setup
from setuptools.dist import Distribution
from packaging.version import parse
from collections import defaultdict
import fnmatch
import inspect
import os
from os.path import dirname, join as pjoin, relpath
from pathlib import Path
import shutil
import sys
SETUP_DIR = Path(__file__).parent.resolve()
try:
# SM_FORCE_C is a testing shim to force setup to use C source files
FORCE_C = int(os.environ.get("SM_FORCE_C", 0))
if FORCE_C:
raise ImportError("Force import error for testing")
from Cython import Tempita, __version__ as cython_version
from Cython.Build import cythonize
from Cython.Distutils import build_ext
HAS_CYTHON = True
CYTHON_3 = parse(cython_version) >= parse("3.0")
except ImportError:
from setuptools.command.build_ext import build_ext
HAS_CYTHON = CYTHON_3 = False
try:
import numpy # noqa: F401
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
###############################################################################
# Key Values that Change Each Release
###############################################################################
# These are strictly installation requirements. Builds requirements are
# managed in pyproject.toml
INSTALL_REQUIRES = []
with open("requirements.txt", encoding="utf-8") as req:
for line in req.readlines():
INSTALL_REQUIRES.append(line.split("#")[0].strip())
DEVELOP_REQUIRES = []
with open("requirements-dev.txt", encoding="utf-8") as req:
for line in req.readlines():
DEVELOP_REQUIRES.append(line.split("#")[0].strip())
CYTHON_MIN_VER = "0.29.33" # released January 2023
EXTRAS_REQUIRE = {
"build": ["cython>=" + CYTHON_MIN_VER],
"develop": ["cython>=" + CYTHON_MIN_VER] + DEVELOP_REQUIRES,
"docs": [
"sphinx",
"nbconvert",
"jupyter_client",
"ipykernel",
"matplotlib",
"nbformat",
"numpydoc",
"pandas-datareader",
],
}
###############################################################################
# Values that rarely change
###############################################################################
DISTNAME = "statsmodels"
DESCRIPTION = "Statistical computations and models for Python"
README = SETUP_DIR.joinpath("README.rst").read_text()
LONG_DESCRIPTION = README
MAINTAINER = "statsmodels Developers"
MAINTAINER_EMAIL = "pystatsmodels@googlegroups.com"
URL = "https://www.statsmodels.org/"
LICENSE = "BSD License"
DOWNLOAD_URL = ""
PROJECT_URLS = {
"Bug Tracker": "https://github.com/statsmodels/statsmodels/issues",
"Documentation": "https://www.statsmodels.org/stable/index.html",
"Source Code": "https://github.com/statsmodels/statsmodels",
}
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Programming Language :: Cython",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Operating System :: OS Independent",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Natural Language :: English",
"License :: OSI Approved :: BSD License",
"Topic :: Office/Business :: Financial",
"Topic :: Scientific/Engineering",
]
FILES_TO_INCLUDE_IN_PACKAGE = ["LICENSE.txt", "setup.cfg"]
FILES_COPIED_TO_PACKAGE = []
for filename in FILES_TO_INCLUDE_IN_PACKAGE:
if os.path.exists(filename):
dest = os.path.join("statsmodels", filename)
shutil.copy2(filename, dest)
FILES_COPIED_TO_PACKAGE.append(dest)
STATESPACE_RESULTS = "statsmodels.tsa.statespace.tests.results"
ADDITIONAL_PACKAGE_DATA = {
"statsmodels": FILES_TO_INCLUDE_IN_PACKAGE,
"statsmodels.datasets.tests": ["*.zip"],
"statsmodels.iolib.tests.results": ["*.dta"],
"statsmodels.stats.tests.results": ["*.json"],
"statsmodels.tsa.stl.tests.results": ["*.csv"],
"statsmodels.tsa.vector_ar.tests.results": ["*.npz", "*.dat"],
"statsmodels.stats.tests": ["*.txt"],
"statsmodels.stats.libqsturng": ["*.r", "*.txt", "*.dat"],
"statsmodels.stats.libqsturng.tests": ["*.csv", "*.dat"],
"statsmodels.sandbox.regression.tests": ["*.dta", "*.csv"],
STATESPACE_RESULTS: ["*.pkl", "*.csv"],
STATESPACE_RESULTS + ".frbny_nowcast": ["test*.mat"],
STATESPACE_RESULTS + ".frbny_nowcast.Nowcasting.data.US": ["*.csv"],
}
##############################################################################
# Extension Building
##############################################################################
CYTHON_COVERAGE = os.environ.get("SM_CYTHON_COVERAGE", False)
CYTHON_COVERAGE = CYTHON_COVERAGE in ("1", "true", '"true"')
CYTHON_TRACE_NOGIL = str(int(CYTHON_COVERAGE))
if CYTHON_COVERAGE:
print("Building with coverage for Cython code")
COMPILER_DIRECTIVES = {"linetrace": CYTHON_COVERAGE}
DEFINE_MACROS = [
("CYTHON_TRACE_NOGIL", CYTHON_TRACE_NOGIL),
("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION"),
]
exts = dict(
_stl={"source": "statsmodels/tsa/stl/_stl.pyx"},
_exponential_smoothers={
"source": "statsmodels/tsa/holtwinters/_exponential_smoothers.pyx"
}, # noqa: E501
_ets_smooth={
"source": "statsmodels/tsa/exponential_smoothing/_ets_smooth.pyx"
}, # noqa: E501
_innovations={"source": "statsmodels/tsa/_innovations.pyx"},
_hamilton_filter={
"source": "statsmodels/tsa/regime_switching/_hamilton_filter.pyx.in"
}, # noqa: E501
_kim_smoother={
"source": "statsmodels/tsa/regime_switching/_kim_smoother.pyx.in"
}, # noqa: E501
_arma_innovations={
"source": "statsmodels/tsa/innovations/_arma_innovations.pyx.in"
}, # noqa: E501
linbin={"source": "statsmodels/nonparametric/linbin.pyx"},
_qn={"source": "statsmodels/robust/_qn.pyx"},
_smoothers_lowess={
"source": "statsmodels/nonparametric/_smoothers_lowess.pyx"
}, # noqa: E501
)
statespace_exts = [
"statsmodels/tsa/statespace/_initialization.pyx.in",
"statsmodels/tsa/statespace/_representation.pyx.in",
"statsmodels/tsa/statespace/_kalman_filter.pyx.in",
"statsmodels/tsa/statespace/_filters/_conventional.pyx.in",
"statsmodels/tsa/statespace/_filters/_inversions.pyx.in",
"statsmodels/tsa/statespace/_filters/_univariate.pyx.in",
"statsmodels/tsa/statespace/_filters/_univariate_diffuse.pyx.in",
"statsmodels/tsa/statespace/_kalman_smoother.pyx.in",
"statsmodels/tsa/statespace/_smoothers/_alternative.pyx.in",
"statsmodels/tsa/statespace/_smoothers/_classical.pyx.in",
"statsmodels/tsa/statespace/_smoothers/_conventional.pyx.in",
"statsmodels/tsa/statespace/_smoothers/_univariate.pyx.in",
"statsmodels/tsa/statespace/_smoothers/_univariate_diffuse.pyx.in",
"statsmodels/tsa/statespace/_simulation_smoother.pyx.in",
"statsmodels/tsa/statespace/_cfa_simulation_smoother.pyx.in",
"statsmodels/tsa/statespace/_tools.pyx.in",
]
class CleanCommand(Command):
user_options = []
def initialize_options(self) -> None:
pass
def finalize_options(self) -> None:
pass
def run(self) -> None:
msg = """
python setup.py clean is not supported.
Use one of:
* `git clean -xdf` to clean all untracked files
* `git clean -Xdf` to clean untracked files ignored by .gitignore
"""
print(msg)
sys.exit(1)
def update_extension(extension, requires_math=True):
import numpy as np
numpy_includes = [np.get_include()]
extra_incl = pjoin(dirname(inspect.getfile(np.core)), "include")
numpy_includes += [extra_incl]
numpy_includes = list(set(numpy_includes))
numpy_math_libs = {
"include_dirs": [np.get_include()],
"library_dirs": [os.path.join(np.get_include(), '..', 'lib')],
"libraries": ["npymath"]
}
if not hasattr(extension, "include_dirs"):
return
extension.include_dirs = list(set(extension.include_dirs + numpy_includes))
if requires_math:
extension.include_dirs += numpy_math_libs["include_dirs"]
extension.libraries += numpy_math_libs["libraries"]
extension.library_dirs += numpy_math_libs["library_dirs"]
class DeferredBuildExt(build_ext):
"""build_ext command for use when numpy headers are needed."""
def build_extensions(self):
self._update_extensions()
build_ext.build_extensions(self)
def _update_extensions(self):
for extension in self.extensions:
requires_math = extension.name in EXT_REQUIRES_NUMPY_MATH_LIBS
update_extension(extension, requires_math=requires_math)
cmdclass = {"clean": CleanCommand}
if not HAS_NUMPY:
cmdclass["build_ext"] = DeferredBuildExt
def check_source(source_name):
"""Chooses C or pyx source files, and raises if C is needed but missing"""
source_ext = ".pyx"
if not HAS_CYTHON:
source_name = source_name.replace(".pyx.in", ".c")
source_name = source_name.replace(".pyx", ".c")
source_ext = ".c"
if not os.path.exists(source_name):
msg = (
"C source not found. You must have Cython installed to "
"build if the C source files have not been generated."
)
raise OSError(msg)
return source_name, source_ext
def process_tempita(source_name):
"""Runs pyx.in files through tempita is needed"""
if source_name.endswith("pyx.in"):
with open(source_name, encoding="utf-8") as templated:
pyx_template = templated.read()
pyx = Tempita.sub(pyx_template)
pyx_filename = source_name[:-3]
with open(pyx_filename, "w", encoding="utf-8") as pyx_file:
pyx_file.write(pyx)
file_stats = os.stat(source_name)
try:
os.utime(
pyx_filename,
ns=(file_stats.st_atime_ns, file_stats.st_mtime_ns),
)
except AttributeError:
os.utime(pyx_filename, (file_stats.st_atime, file_stats.st_mtime))
source_name = pyx_filename
return source_name
EXT_REQUIRES_NUMPY_MATH_LIBS = []
extensions = []
for config in exts.values():
uses_blas = True
source, ext = check_source(config["source"])
source = process_tempita(source)
name = source.replace("/", ".").replace(ext, "")
include_dirs = config.get("include_dirs", [])
depends = config.get("depends", [])
libraries = config.get("libraries", [])
library_dirs = config.get("library_dirs", [])
uses_numpy_libraries = config.get("numpy_libraries", False)
if uses_blas or uses_numpy_libraries:
EXT_REQUIRES_NUMPY_MATH_LIBS.append(name)
ext = Extension(
name,
[source],
include_dirs=include_dirs,
depends=depends,
libraries=libraries,
library_dirs=library_dirs,
define_macros=DEFINE_MACROS,
)
extensions.append(ext)
for source in statespace_exts:
source, ext = check_source(source)
source = process_tempita(source)
name = source.replace("/", ".").replace(ext, "")
EXT_REQUIRES_NUMPY_MATH_LIBS.append(name)
ext = Extension(
name,
[source],
include_dirs=["statsmodels/src"],
depends=[],
libraries=[],
library_dirs=[],
define_macros=DEFINE_MACROS,
)
extensions.append(ext)
if HAS_NUMPY:
for extension in extensions:
requires_math = extension.name in EXT_REQUIRES_NUMPY_MATH_LIBS
update_extension(extension, requires_math=requires_math)
if HAS_CYTHON:
if CYTHON_3:
COMPILER_DIRECTIVES["cpow"] = True
extensions = cythonize(
extensions,
compiler_directives=COMPILER_DIRECTIVES,
language_level=3,
force=CYTHON_COVERAGE,
)
##############################################################################
# Construct package data
##############################################################################
package_data = defaultdict(list)
filetypes = ["*.csv", "*.txt", "*.dta"]
for root, _, filenames in os.walk(
pjoin(os.getcwd(), "statsmodels", "datasets")
): # noqa: E501
matches = []
for filetype in filetypes:
for filename in fnmatch.filter(filenames, filetype):
matches.append(filename)
if matches:
package_data[".".join(relpath(root).split(os.path.sep))] = filetypes
for root, _, _ in os.walk(pjoin(os.getcwd(), "statsmodels")):
if root.endswith("results"):
package_data[".".join(relpath(root).split(os.path.sep))] = filetypes
for path, filetypes in ADDITIONAL_PACKAGE_DATA.items():
package_data[path].extend(filetypes)
if os.path.exists("MANIFEST"):
os.unlink("MANIFEST")
class BinaryDistribution(Distribution):
def is_pure(self):
return False
setup(
name=DISTNAME,
maintainer=MAINTAINER,
ext_modules=extensions,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
license=LICENSE,
url=URL,
download_url=DOWNLOAD_URL,
project_urls=PROJECT_URLS,
long_description=LONG_DESCRIPTION,
classifiers=CLASSIFIERS,
platforms="any",
cmdclass=cmdclass,
packages=find_packages(),
package_data=package_data,
distclass=BinaryDistribution,
include_package_data=False, # True will install all files in repo
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRE,
zip_safe=False,
python_requires=">=3.9",
)
# Clean-up copied files
for copy in FILES_COPIED_TO_PACKAGE:
os.unlink(copy)