setup.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. import os
  2. import sys
  3. import pickle
  4. import copy
  5. import warnings
  6. import platform
  7. import textwrap
  8. from os.path import join
  9. from numpy.distutils import log
  10. from distutils.dep_util import newer
  11. from sysconfig import get_config_var
  12. from numpy.compat import npy_load_module
  13. from setup_common import * # noqa: F403
  14. # Set to True to enable relaxed strides checking. This (mostly) means
  15. # that `strides[dim]` is ignored if `shape[dim] == 1` when setting flags.
  16. NPY_RELAXED_STRIDES_CHECKING = (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', "1") != "0")
  17. # Put NPY_RELAXED_STRIDES_DEBUG=1 in the environment if you want numpy to use a
  18. # bogus value for affected strides in order to help smoke out bad stride usage
  19. # when relaxed stride checking is enabled.
  20. NPY_RELAXED_STRIDES_DEBUG = (os.environ.get('NPY_RELAXED_STRIDES_DEBUG', "0") != "0")
  21. NPY_RELAXED_STRIDES_DEBUG = NPY_RELAXED_STRIDES_DEBUG and NPY_RELAXED_STRIDES_CHECKING
  22. # Set to True to use the new casting implementation as much as implemented.
  23. # Allows running the full test suit to exercise the new machinery until
  24. # it is used as default and the old version is eventually deleted.
  25. NPY_USE_NEW_CASTINGIMPL = os.environ.get('NPY_USE_NEW_CASTINGIMPL', "0") != "0"
  26. # XXX: ugly, we use a class to avoid calling twice some expensive functions in
  27. # config.h/numpyconfig.h. I don't see a better way because distutils force
  28. # config.h generation inside an Extension class, and as such sharing
  29. # configuration information between extensions is not easy.
  30. # Using a pickled-based memoize does not work because config_cmd is an instance
  31. # method, which cPickle does not like.
  32. #
  33. # Use pickle in all cases, as cPickle is gone in python3 and the difference
  34. # in time is only in build. -- Charles Harris, 2013-03-30
  35. class CallOnceOnly:
  36. def __init__(self):
  37. self._check_types = None
  38. self._check_ieee_macros = None
  39. self._check_complex = None
  40. def check_types(self, *a, **kw):
  41. if self._check_types is None:
  42. out = check_types(*a, **kw)
  43. self._check_types = pickle.dumps(out)
  44. else:
  45. out = copy.deepcopy(pickle.loads(self._check_types))
  46. return out
  47. def check_ieee_macros(self, *a, **kw):
  48. if self._check_ieee_macros is None:
  49. out = check_ieee_macros(*a, **kw)
  50. self._check_ieee_macros = pickle.dumps(out)
  51. else:
  52. out = copy.deepcopy(pickle.loads(self._check_ieee_macros))
  53. return out
  54. def check_complex(self, *a, **kw):
  55. if self._check_complex is None:
  56. out = check_complex(*a, **kw)
  57. self._check_complex = pickle.dumps(out)
  58. else:
  59. out = copy.deepcopy(pickle.loads(self._check_complex))
  60. return out
  61. def pythonlib_dir():
  62. """return path where libpython* is."""
  63. if sys.platform == 'win32':
  64. return os.path.join(sys.prefix, "libs")
  65. else:
  66. return get_config_var('LIBDIR')
  67. def is_npy_no_signal():
  68. """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration
  69. header."""
  70. return sys.platform == 'win32'
  71. def is_npy_no_smp():
  72. """Return True if the NPY_NO_SMP symbol must be defined in public
  73. header (when SMP support cannot be reliably enabled)."""
  74. # Perhaps a fancier check is in order here.
  75. # so that threads are only enabled if there
  76. # are actually multiple CPUS? -- but
  77. # threaded code can be nice even on a single
  78. # CPU so that long-calculating code doesn't
  79. # block.
  80. return 'NPY_NOSMP' in os.environ
  81. def win32_checks(deflist):
  82. from numpy.distutils.misc_util import get_build_architecture
  83. a = get_build_architecture()
  84. # Distutils hack on AMD64 on windows
  85. print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' %
  86. (a, os.name, sys.platform))
  87. if a == 'AMD64':
  88. deflist.append('DISTUTILS_USE_SDK')
  89. # On win32, force long double format string to be 'g', not
  90. # 'Lg', since the MS runtime does not support long double whose
  91. # size is > sizeof(double)
  92. if a == "Intel" or a == "AMD64":
  93. deflist.append('FORCE_NO_LONG_DOUBLE_FORMATTING')
  94. def check_math_capabilities(config, ext, moredefs, mathlibs):
  95. def check_func(func_name):
  96. return config.check_func(func_name, libraries=mathlibs,
  97. decl=True, call=True)
  98. def check_funcs_once(funcs_name):
  99. decl = dict([(f, True) for f in funcs_name])
  100. st = config.check_funcs_once(funcs_name, libraries=mathlibs,
  101. decl=decl, call=decl)
  102. if st:
  103. moredefs.extend([(fname2def(f), 1) for f in funcs_name])
  104. return st
  105. def check_funcs(funcs_name):
  106. # Use check_funcs_once first, and if it does not work, test func per
  107. # func. Return success only if all the functions are available
  108. if not check_funcs_once(funcs_name):
  109. # Global check failed, check func per func
  110. for f in funcs_name:
  111. if check_func(f):
  112. moredefs.append((fname2def(f), 1))
  113. return 0
  114. else:
  115. return 1
  116. #use_msvc = config.check_decl("_MSC_VER")
  117. if not check_funcs_once(MANDATORY_FUNCS):
  118. raise SystemError("One of the required function to build numpy is not"
  119. " available (the list is %s)." % str(MANDATORY_FUNCS))
  120. # Standard functions which may not be available and for which we have a
  121. # replacement implementation. Note that some of these are C99 functions.
  122. # XXX: hack to circumvent cpp pollution from python: python put its
  123. # config.h in the public namespace, so we have a clash for the common
  124. # functions we test. We remove every function tested by python's
  125. # autoconf, hoping their own test are correct
  126. for f in OPTIONAL_STDFUNCS_MAYBE:
  127. if config.check_decl(fname2def(f),
  128. headers=["Python.h", "math.h"]):
  129. OPTIONAL_STDFUNCS.remove(f)
  130. check_funcs(OPTIONAL_STDFUNCS)
  131. for h in OPTIONAL_HEADERS:
  132. if config.check_func("", decl=False, call=False, headers=[h]):
  133. h = h.replace(".", "_").replace(os.path.sep, "_")
  134. moredefs.append((fname2def(h), 1))
  135. for tup in OPTIONAL_INTRINSICS:
  136. headers = None
  137. if len(tup) == 2:
  138. f, args, m = tup[0], tup[1], fname2def(tup[0])
  139. elif len(tup) == 3:
  140. f, args, headers, m = tup[0], tup[1], [tup[2]], fname2def(tup[0])
  141. else:
  142. f, args, headers, m = tup[0], tup[1], [tup[2]], fname2def(tup[3])
  143. if config.check_func(f, decl=False, call=True, call_args=args,
  144. headers=headers):
  145. moredefs.append((m, 1))
  146. for dec, fn in OPTIONAL_FUNCTION_ATTRIBUTES:
  147. if config.check_gcc_function_attribute(dec, fn):
  148. moredefs.append((fname2def(fn), 1))
  149. if fn == 'attribute_target_avx512f':
  150. # GH-14787: Work around GCC<8.4 bug when compiling with AVX512
  151. # support on Windows-based platforms
  152. if (sys.platform in ('win32', 'cygwin') and
  153. config.check_compiler_gcc() and
  154. not config.check_gcc_version_at_least(8, 4)):
  155. ext.extra_compile_args.extend(
  156. ['-ffixed-xmm%s' % n for n in range(16, 32)])
  157. for dec, fn, code, header in OPTIONAL_FUNCTION_ATTRIBUTES_WITH_INTRINSICS:
  158. if config.check_gcc_function_attribute_with_intrinsics(dec, fn, code,
  159. header):
  160. moredefs.append((fname2def(fn), 1))
  161. for fn in OPTIONAL_VARIABLE_ATTRIBUTES:
  162. if config.check_gcc_variable_attribute(fn):
  163. m = fn.replace("(", "_").replace(")", "_")
  164. moredefs.append((fname2def(m), 1))
  165. # C99 functions: float and long double versions
  166. check_funcs(C99_FUNCS_SINGLE)
  167. check_funcs(C99_FUNCS_EXTENDED)
  168. def check_complex(config, mathlibs):
  169. priv = []
  170. pub = []
  171. try:
  172. if os.uname()[0] == "Interix":
  173. warnings.warn("Disabling broken complex support. See #1365", stacklevel=2)
  174. return priv, pub
  175. except Exception:
  176. # os.uname not available on all platforms. blanket except ugly but safe
  177. pass
  178. # Check for complex support
  179. st = config.check_header('complex.h')
  180. if st:
  181. priv.append(('HAVE_COMPLEX_H', 1))
  182. pub.append(('NPY_USE_C99_COMPLEX', 1))
  183. for t in C99_COMPLEX_TYPES:
  184. st = config.check_type(t, headers=["complex.h"])
  185. if st:
  186. pub.append(('NPY_HAVE_%s' % type2def(t), 1))
  187. def check_prec(prec):
  188. flist = [f + prec for f in C99_COMPLEX_FUNCS]
  189. decl = dict([(f, True) for f in flist])
  190. if not config.check_funcs_once(flist, call=decl, decl=decl,
  191. libraries=mathlibs):
  192. for f in flist:
  193. if config.check_func(f, call=True, decl=True,
  194. libraries=mathlibs):
  195. priv.append((fname2def(f), 1))
  196. else:
  197. priv.extend([(fname2def(f), 1) for f in flist])
  198. check_prec('')
  199. check_prec('f')
  200. check_prec('l')
  201. return priv, pub
  202. def check_ieee_macros(config):
  203. priv = []
  204. pub = []
  205. macros = []
  206. def _add_decl(f):
  207. priv.append(fname2def("decl_%s" % f))
  208. pub.append('NPY_%s' % fname2def("decl_%s" % f))
  209. # XXX: hack to circumvent cpp pollution from python: python put its
  210. # config.h in the public namespace, so we have a clash for the common
  211. # functions we test. We remove every function tested by python's
  212. # autoconf, hoping their own test are correct
  213. _macros = ["isnan", "isinf", "signbit", "isfinite"]
  214. for f in _macros:
  215. py_symbol = fname2def("decl_%s" % f)
  216. already_declared = config.check_decl(py_symbol,
  217. headers=["Python.h", "math.h"])
  218. if already_declared:
  219. if config.check_macro_true(py_symbol,
  220. headers=["Python.h", "math.h"]):
  221. pub.append('NPY_%s' % fname2def("decl_%s" % f))
  222. else:
  223. macros.append(f)
  224. # Normally, isnan and isinf are macro (C99), but some platforms only have
  225. # func, or both func and macro version. Check for macro only, and define
  226. # replacement ones if not found.
  227. # Note: including Python.h is necessary because it modifies some math.h
  228. # definitions
  229. for f in macros:
  230. st = config.check_decl(f, headers=["Python.h", "math.h"])
  231. if st:
  232. _add_decl(f)
  233. return priv, pub
  234. def check_types(config_cmd, ext, build_dir):
  235. private_defines = []
  236. public_defines = []
  237. # Expected size (in number of bytes) for each type. This is an
  238. # optimization: those are only hints, and an exhaustive search for the size
  239. # is done if the hints are wrong.
  240. expected = {'short': [2], 'int': [4], 'long': [8, 4],
  241. 'float': [4], 'double': [8], 'long double': [16, 12, 8],
  242. 'Py_intptr_t': [8, 4], 'PY_LONG_LONG': [8], 'long long': [8],
  243. 'off_t': [8, 4]}
  244. # Check we have the python header (-dev* packages on Linux)
  245. result = config_cmd.check_header('Python.h')
  246. if not result:
  247. python = 'python'
  248. if '__pypy__' in sys.builtin_module_names:
  249. python = 'pypy'
  250. raise SystemError(
  251. "Cannot compile 'Python.h'. Perhaps you need to "
  252. "install {0}-dev|{0}-devel.".format(python))
  253. res = config_cmd.check_header("endian.h")
  254. if res:
  255. private_defines.append(('HAVE_ENDIAN_H', 1))
  256. public_defines.append(('NPY_HAVE_ENDIAN_H', 1))
  257. res = config_cmd.check_header("sys/endian.h")
  258. if res:
  259. private_defines.append(('HAVE_SYS_ENDIAN_H', 1))
  260. public_defines.append(('NPY_HAVE_SYS_ENDIAN_H', 1))
  261. # Check basic types sizes
  262. for type in ('short', 'int', 'long'):
  263. res = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers=["Python.h"])
  264. if res:
  265. public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), "SIZEOF_%s" % sym2def(type)))
  266. else:
  267. res = config_cmd.check_type_size(type, expected=expected[type])
  268. if res >= 0:
  269. public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
  270. else:
  271. raise SystemError("Checking sizeof (%s) failed !" % type)
  272. for type in ('float', 'double', 'long double'):
  273. already_declared = config_cmd.check_decl("SIZEOF_%s" % sym2def(type),
  274. headers=["Python.h"])
  275. res = config_cmd.check_type_size(type, expected=expected[type])
  276. if res >= 0:
  277. public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
  278. if not already_declared and not type == 'long double':
  279. private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))
  280. else:
  281. raise SystemError("Checking sizeof (%s) failed !" % type)
  282. # Compute size of corresponding complex type: used to check that our
  283. # definition is binary compatible with C99 complex type (check done at
  284. # build time in npy_common.h)
  285. complex_def = "struct {%s __x; %s __y;}" % (type, type)
  286. res = config_cmd.check_type_size(complex_def,
  287. expected=[2 * x for x in expected[type]])
  288. if res >= 0:
  289. public_defines.append(('NPY_SIZEOF_COMPLEX_%s' % sym2def(type), '%d' % res))
  290. else:
  291. raise SystemError("Checking sizeof (%s) failed !" % complex_def)
  292. for type in ('Py_intptr_t', 'off_t'):
  293. res = config_cmd.check_type_size(type, headers=["Python.h"],
  294. library_dirs=[pythonlib_dir()],
  295. expected=expected[type])
  296. if res >= 0:
  297. private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))
  298. public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
  299. else:
  300. raise SystemError("Checking sizeof (%s) failed !" % type)
  301. # We check declaration AND type because that's how distutils does it.
  302. if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']):
  303. res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'],
  304. library_dirs=[pythonlib_dir()],
  305. expected=expected['PY_LONG_LONG'])
  306. if res >= 0:
  307. private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))
  308. public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))
  309. else:
  310. raise SystemError("Checking sizeof (%s) failed !" % 'PY_LONG_LONG')
  311. res = config_cmd.check_type_size('long long',
  312. expected=expected['long long'])
  313. if res >= 0:
  314. #private_defines.append(('SIZEOF_%s' % sym2def('long long'), '%d' % res))
  315. public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res))
  316. else:
  317. raise SystemError("Checking sizeof (%s) failed !" % 'long long')
  318. if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']):
  319. raise RuntimeError(
  320. "Config wo CHAR_BIT is not supported"
  321. ", please contact the maintainers")
  322. return private_defines, public_defines
  323. def check_mathlib(config_cmd):
  324. # Testing the C math library
  325. mathlibs = []
  326. mathlibs_choices = [[], ['m'], ['cpml']]
  327. mathlib = os.environ.get('MATHLIB')
  328. if mathlib:
  329. mathlibs_choices.insert(0, mathlib.split(','))
  330. for libs in mathlibs_choices:
  331. if config_cmd.check_func("exp", libraries=libs, decl=True, call=True):
  332. mathlibs = libs
  333. break
  334. else:
  335. raise EnvironmentError("math library missing; rerun "
  336. "setup.py after setting the "
  337. "MATHLIB env variable")
  338. return mathlibs
  339. def visibility_define(config):
  340. """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
  341. string)."""
  342. hide = '__attribute__((visibility("hidden")))'
  343. if config.check_gcc_function_attribute(hide, 'hideme'):
  344. return hide
  345. else:
  346. return ''
  347. def configuration(parent_package='',top_path=None):
  348. from numpy.distutils.misc_util import Configuration, dot_join
  349. from numpy.distutils.system_info import (get_info, blas_opt_info,
  350. lapack_opt_info)
  351. # Accelerate is buggy, disallow it. See also numpy/linalg/setup.py
  352. for opt_order in (blas_opt_info.blas_order, lapack_opt_info.lapack_order):
  353. if 'accelerate' in opt_order:
  354. opt_order.remove('accelerate')
  355. config = Configuration('core', parent_package, top_path)
  356. local_dir = config.local_path
  357. codegen_dir = join(local_dir, 'code_generators')
  358. if is_released(config):
  359. warnings.simplefilter('error', MismatchCAPIWarning)
  360. # Check whether we have a mismatch between the set C API VERSION and the
  361. # actual C API VERSION
  362. check_api_version(C_API_VERSION, codegen_dir)
  363. generate_umath_py = join(codegen_dir, 'generate_umath.py')
  364. n = dot_join(config.name, 'generate_umath')
  365. generate_umath = npy_load_module('_'.join(n.split('.')),
  366. generate_umath_py, ('.py', 'U', 1))
  367. header_dir = 'include/numpy' # this is relative to config.path_in_package
  368. cocache = CallOnceOnly()
  369. def generate_config_h(ext, build_dir):
  370. target = join(build_dir, header_dir, 'config.h')
  371. d = os.path.dirname(target)
  372. if not os.path.exists(d):
  373. os.makedirs(d)
  374. if newer(__file__, target):
  375. config_cmd = config.get_config_cmd()
  376. log.info('Generating %s', target)
  377. # Check sizeof
  378. moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir)
  379. # Check math library and C99 math funcs availability
  380. mathlibs = check_mathlib(config_cmd)
  381. moredefs.append(('MATHLIB', ','.join(mathlibs)))
  382. check_math_capabilities(config_cmd, ext, moredefs, mathlibs)
  383. moredefs.extend(cocache.check_ieee_macros(config_cmd)[0])
  384. moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[0])
  385. # Signal check
  386. if is_npy_no_signal():
  387. moredefs.append('__NPY_PRIVATE_NO_SIGNAL')
  388. # Windows checks
  389. if sys.platform == 'win32' or os.name == 'nt':
  390. win32_checks(moredefs)
  391. # C99 restrict keyword
  392. moredefs.append(('NPY_RESTRICT', config_cmd.check_restrict()))
  393. # Inline check
  394. inline = config_cmd.check_inline()
  395. # Use relaxed stride checking
  396. if NPY_RELAXED_STRIDES_CHECKING:
  397. moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1))
  398. # Use bogus stride debug aid when relaxed strides are enabled
  399. if NPY_RELAXED_STRIDES_DEBUG:
  400. moredefs.append(('NPY_RELAXED_STRIDES_DEBUG', 1))
  401. # Use the new experimental casting implementation in NumPy 1.20:
  402. if NPY_USE_NEW_CASTINGIMPL:
  403. moredefs.append(('NPY_USE_NEW_CASTINGIMPL', 1))
  404. # Get long double representation
  405. rep = check_long_double_representation(config_cmd)
  406. moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1))
  407. if check_for_right_shift_internal_compiler_error(config_cmd):
  408. moredefs.append('NPY_DO_NOT_OPTIMIZE_LONG_right_shift')
  409. moredefs.append('NPY_DO_NOT_OPTIMIZE_ULONG_right_shift')
  410. moredefs.append('NPY_DO_NOT_OPTIMIZE_LONGLONG_right_shift')
  411. moredefs.append('NPY_DO_NOT_OPTIMIZE_ULONGLONG_right_shift')
  412. # Generate the config.h file from moredefs
  413. with open(target, 'w') as target_f:
  414. for d in moredefs:
  415. if isinstance(d, str):
  416. target_f.write('#define %s\n' % (d))
  417. else:
  418. target_f.write('#define %s %s\n' % (d[0], d[1]))
  419. # define inline to our keyword, or nothing
  420. target_f.write('#ifndef __cplusplus\n')
  421. if inline == 'inline':
  422. target_f.write('/* #undef inline */\n')
  423. else:
  424. target_f.write('#define inline %s\n' % inline)
  425. target_f.write('#endif\n')
  426. # add the guard to make sure config.h is never included directly,
  427. # but always through npy_config.h
  428. target_f.write(textwrap.dedent("""
  429. #ifndef _NPY_NPY_CONFIG_H_
  430. #error config.h should never be included directly, include npy_config.h instead
  431. #endif
  432. """))
  433. log.info('File: %s' % target)
  434. with open(target) as target_f:
  435. log.info(target_f.read())
  436. log.info('EOF')
  437. else:
  438. mathlibs = []
  439. with open(target) as target_f:
  440. for line in target_f:
  441. s = '#define MATHLIB'
  442. if line.startswith(s):
  443. value = line[len(s):].strip()
  444. if value:
  445. mathlibs.extend(value.split(','))
  446. # Ugly: this can be called within a library and not an extension,
  447. # in which case there is no libraries attributes (and none is
  448. # needed).
  449. if hasattr(ext, 'libraries'):
  450. ext.libraries.extend(mathlibs)
  451. incl_dir = os.path.dirname(target)
  452. if incl_dir not in config.numpy_include_dirs:
  453. config.numpy_include_dirs.append(incl_dir)
  454. return target
  455. def generate_numpyconfig_h(ext, build_dir):
  456. """Depends on config.h: generate_config_h has to be called before !"""
  457. # put common include directory in build_dir on search path
  458. # allows using code generation in headers
  459. config.add_include_dirs(join(build_dir, "src", "common"))
  460. config.add_include_dirs(join(build_dir, "src", "npymath"))
  461. target = join(build_dir, header_dir, '_numpyconfig.h')
  462. d = os.path.dirname(target)
  463. if not os.path.exists(d):
  464. os.makedirs(d)
  465. if newer(__file__, target):
  466. config_cmd = config.get_config_cmd()
  467. log.info('Generating %s', target)
  468. # Check sizeof
  469. ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir)
  470. if is_npy_no_signal():
  471. moredefs.append(('NPY_NO_SIGNAL', 1))
  472. if is_npy_no_smp():
  473. moredefs.append(('NPY_NO_SMP', 1))
  474. else:
  475. moredefs.append(('NPY_NO_SMP', 0))
  476. mathlibs = check_mathlib(config_cmd)
  477. moredefs.extend(cocache.check_ieee_macros(config_cmd)[1])
  478. moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[1])
  479. if NPY_RELAXED_STRIDES_CHECKING:
  480. moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1))
  481. if NPY_RELAXED_STRIDES_DEBUG:
  482. moredefs.append(('NPY_RELAXED_STRIDES_DEBUG', 1))
  483. # Check whether we can use inttypes (C99) formats
  484. if config_cmd.check_decl('PRIdPTR', headers=['inttypes.h']):
  485. moredefs.append(('NPY_USE_C99_FORMATS', 1))
  486. # visibility check
  487. hidden_visibility = visibility_define(config_cmd)
  488. moredefs.append(('NPY_VISIBILITY_HIDDEN', hidden_visibility))
  489. # Add the C API/ABI versions
  490. moredefs.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION))
  491. moredefs.append(('NPY_API_VERSION', '0x%.8X' % C_API_VERSION))
  492. # Add moredefs to header
  493. with open(target, 'w') as target_f:
  494. for d in moredefs:
  495. if isinstance(d, str):
  496. target_f.write('#define %s\n' % (d))
  497. else:
  498. target_f.write('#define %s %s\n' % (d[0], d[1]))
  499. # Define __STDC_FORMAT_MACROS
  500. target_f.write(textwrap.dedent("""
  501. #ifndef __STDC_FORMAT_MACROS
  502. #define __STDC_FORMAT_MACROS 1
  503. #endif
  504. """))
  505. # Dump the numpyconfig.h header to stdout
  506. log.info('File: %s' % target)
  507. with open(target) as target_f:
  508. log.info(target_f.read())
  509. log.info('EOF')
  510. config.add_data_files((header_dir, target))
  511. return target
  512. def generate_api_func(module_name):
  513. def generate_api(ext, build_dir):
  514. script = join(codegen_dir, module_name + '.py')
  515. sys.path.insert(0, codegen_dir)
  516. try:
  517. m = __import__(module_name)
  518. log.info('executing %s', script)
  519. h_file, c_file, doc_file = m.generate_api(os.path.join(build_dir, header_dir))
  520. finally:
  521. del sys.path[0]
  522. config.add_data_files((header_dir, h_file),
  523. (header_dir, doc_file))
  524. return (h_file,)
  525. return generate_api
  526. generate_numpy_api = generate_api_func('generate_numpy_api')
  527. generate_ufunc_api = generate_api_func('generate_ufunc_api')
  528. config.add_include_dirs(join(local_dir, "src", "common"))
  529. config.add_include_dirs(join(local_dir, "src"))
  530. config.add_include_dirs(join(local_dir))
  531. config.add_data_dir('include/numpy')
  532. config.add_include_dirs(join('src', 'npymath'))
  533. config.add_include_dirs(join('src', 'multiarray'))
  534. config.add_include_dirs(join('src', 'umath'))
  535. config.add_include_dirs(join('src', 'npysort'))
  536. config.add_include_dirs(join('src', '_simd'))
  537. config.add_define_macros([("NPY_INTERNAL_BUILD", "1")]) # this macro indicates that Numpy build is in process
  538. config.add_define_macros([("HAVE_NPY_CONFIG_H", "1")])
  539. if sys.platform[:3] == "aix":
  540. config.add_define_macros([("_LARGE_FILES", None)])
  541. else:
  542. config.add_define_macros([("_FILE_OFFSET_BITS", "64")])
  543. config.add_define_macros([('_LARGEFILE_SOURCE', '1')])
  544. config.add_define_macros([('_LARGEFILE64_SOURCE', '1')])
  545. config.numpy_include_dirs.extend(config.paths('include'))
  546. deps = [join('src', 'npymath', '_signbit.c'),
  547. join('include', 'numpy', '*object.h'),
  548. join(codegen_dir, 'genapi.py'),
  549. ]
  550. #######################################################################
  551. # npymath library #
  552. #######################################################################
  553. subst_dict = dict([("sep", os.path.sep), ("pkgname", "numpy.core")])
  554. def get_mathlib_info(*args):
  555. # Another ugly hack: the mathlib info is known once build_src is run,
  556. # but we cannot use add_installed_pkg_config here either, so we only
  557. # update the substitution dictionary during npymath build
  558. config_cmd = config.get_config_cmd()
  559. # Check that the toolchain works, to fail early if it doesn't
  560. # (avoid late errors with MATHLIB which are confusing if the
  561. # compiler does not work).
  562. st = config_cmd.try_link('int main(void) { return 0;}')
  563. if not st:
  564. # rerun the failing command in verbose mode
  565. config_cmd.compiler.verbose = True
  566. config_cmd.try_link('int main(void) { return 0;}')
  567. raise RuntimeError("Broken toolchain: cannot link a simple C program")
  568. mlibs = check_mathlib(config_cmd)
  569. posix_mlib = ' '.join(['-l%s' % l for l in mlibs])
  570. msvc_mlib = ' '.join(['%s.lib' % l for l in mlibs])
  571. subst_dict["posix_mathlib"] = posix_mlib
  572. subst_dict["msvc_mathlib"] = msvc_mlib
  573. npymath_sources = [join('src', 'npymath', 'npy_math_internal.h.src'),
  574. join('src', 'npymath', 'npy_math.c'),
  575. join('src', 'npymath', 'ieee754.c.src'),
  576. join('src', 'npymath', 'npy_math_complex.c.src'),
  577. join('src', 'npymath', 'halffloat.c')
  578. ]
  579. # Must be true for CRT compilers but not MinGW/cygwin. See gh-9977.
  580. # Intel and Clang also don't seem happy with /GL
  581. is_msvc = (platform.platform().startswith('Windows') and
  582. platform.python_compiler().startswith('MS'))
  583. config.add_installed_library('npymath',
  584. sources=npymath_sources + [get_mathlib_info],
  585. install_dir='lib',
  586. build_info={
  587. 'include_dirs' : [], # empty list required for creating npy_math_internal.h
  588. 'extra_compiler_args' : (['/GL-'] if is_msvc else []),
  589. })
  590. config.add_npy_pkg_config("npymath.ini.in", "lib/npy-pkg-config",
  591. subst_dict)
  592. config.add_npy_pkg_config("mlib.ini.in", "lib/npy-pkg-config",
  593. subst_dict)
  594. #######################################################################
  595. # multiarray_tests module #
  596. #######################################################################
  597. config.add_extension('_multiarray_tests',
  598. sources=[join('src', 'multiarray', '_multiarray_tests.c.src'),
  599. join('src', 'common', 'mem_overlap.c')],
  600. depends=[join('src', 'common', 'mem_overlap.h'),
  601. join('src', 'common', 'npy_extint128.h')],
  602. libraries=['npymath'])
  603. #######################################################################
  604. # _multiarray_umath module - common part #
  605. #######################################################################
  606. common_deps = [
  607. join('src', 'common', 'array_assign.h'),
  608. join('src', 'common', 'binop_override.h'),
  609. join('src', 'common', 'cblasfuncs.h'),
  610. join('src', 'common', 'lowlevel_strided_loops.h'),
  611. join('src', 'common', 'mem_overlap.h'),
  612. join('src', 'common', 'npy_cblas.h'),
  613. join('src', 'common', 'npy_config.h'),
  614. join('src', 'common', 'npy_ctypes.h'),
  615. join('src', 'common', 'npy_extint128.h'),
  616. join('src', 'common', 'npy_import.h'),
  617. join('src', 'common', 'npy_longdouble.h'),
  618. join('src', 'common', 'templ_common.h.src'),
  619. join('src', 'common', 'ucsnarrow.h'),
  620. join('src', 'common', 'ufunc_override.h'),
  621. join('src', 'common', 'umathmodule.h'),
  622. join('src', 'common', 'numpyos.h'),
  623. join('src', 'common', 'npy_cpu_dispatch.h'),
  624. join('src', 'common', 'simd', 'simd.h'),
  625. ]
  626. common_src = [
  627. join('src', 'common', 'array_assign.c'),
  628. join('src', 'common', 'mem_overlap.c'),
  629. join('src', 'common', 'npy_longdouble.c'),
  630. join('src', 'common', 'templ_common.h.src'),
  631. join('src', 'common', 'ucsnarrow.c'),
  632. join('src', 'common', 'ufunc_override.c'),
  633. join('src', 'common', 'numpyos.c'),
  634. join('src', 'common', 'npy_cpu_features.c.src'),
  635. ]
  636. if os.environ.get('NPY_USE_BLAS_ILP64', "0") != "0":
  637. blas_info = get_info('blas_ilp64_opt', 2)
  638. else:
  639. blas_info = get_info('blas_opt', 0)
  640. have_blas = blas_info and ('HAVE_CBLAS', None) in blas_info.get('define_macros', [])
  641. if have_blas:
  642. extra_info = blas_info
  643. # These files are also in MANIFEST.in so that they are always in
  644. # the source distribution independently of HAVE_CBLAS.
  645. common_src.extend([join('src', 'common', 'cblasfuncs.c'),
  646. join('src', 'common', 'python_xerbla.c'),
  647. ])
  648. else:
  649. extra_info = {}
  650. #######################################################################
  651. # _multiarray_umath module - multiarray part #
  652. #######################################################################
  653. multiarray_deps = [
  654. join('src', 'multiarray', 'abstractdtypes.h'),
  655. join('src', 'multiarray', 'arrayobject.h'),
  656. join('src', 'multiarray', 'arraytypes.h'),
  657. join('src', 'multiarray', 'arrayfunction_override.h'),
  658. join('src', 'multiarray', 'array_coercion.h'),
  659. join('src', 'multiarray', 'array_method.h'),
  660. join('src', 'multiarray', 'npy_buffer.h'),
  661. join('src', 'multiarray', 'calculation.h'),
  662. join('src', 'multiarray', 'common.h'),
  663. join('src', 'multiarray', 'convert_datatype.h'),
  664. join('src', 'multiarray', 'convert.h'),
  665. join('src', 'multiarray', 'conversion_utils.h'),
  666. join('src', 'multiarray', 'ctors.h'),
  667. join('src', 'multiarray', 'descriptor.h'),
  668. join('src', 'multiarray', 'dtypemeta.h'),
  669. join('src', 'multiarray', 'dragon4.h'),
  670. join('src', 'multiarray', 'einsum_debug.h'),
  671. join('src', 'multiarray', 'einsum_sumprod.h'),
  672. join('src', 'multiarray', 'getset.h'),
  673. join('src', 'multiarray', 'hashdescr.h'),
  674. join('src', 'multiarray', 'iterators.h'),
  675. join('src', 'multiarray', 'legacy_dtype_implementation.h'),
  676. join('src', 'multiarray', 'mapping.h'),
  677. join('src', 'multiarray', 'methods.h'),
  678. join('src', 'multiarray', 'multiarraymodule.h'),
  679. join('src', 'multiarray', 'nditer_impl.h'),
  680. join('src', 'multiarray', 'number.h'),
  681. join('src', 'multiarray', 'refcount.h'),
  682. join('src', 'multiarray', 'scalartypes.h'),
  683. join('src', 'multiarray', 'sequence.h'),
  684. join('src', 'multiarray', 'shape.h'),
  685. join('src', 'multiarray', 'strfuncs.h'),
  686. join('src', 'multiarray', 'typeinfo.h'),
  687. join('src', 'multiarray', 'usertypes.h'),
  688. join('src', 'multiarray', 'vdot.h'),
  689. join('include', 'numpy', 'arrayobject.h'),
  690. join('include', 'numpy', '_neighborhood_iterator_imp.h'),
  691. join('include', 'numpy', 'npy_endian.h'),
  692. join('include', 'numpy', 'arrayscalars.h'),
  693. join('include', 'numpy', 'noprefix.h'),
  694. join('include', 'numpy', 'npy_interrupt.h'),
  695. join('include', 'numpy', 'npy_3kcompat.h'),
  696. join('include', 'numpy', 'npy_math.h'),
  697. join('include', 'numpy', 'halffloat.h'),
  698. join('include', 'numpy', 'npy_common.h'),
  699. join('include', 'numpy', 'npy_os.h'),
  700. join('include', 'numpy', 'utils.h'),
  701. join('include', 'numpy', 'ndarrayobject.h'),
  702. join('include', 'numpy', 'npy_cpu.h'),
  703. join('include', 'numpy', 'numpyconfig.h'),
  704. join('include', 'numpy', 'ndarraytypes.h'),
  705. join('include', 'numpy', 'npy_1_7_deprecated_api.h'),
  706. # add library sources as distuils does not consider libraries
  707. # dependencies
  708. ] + npymath_sources
  709. multiarray_src = [
  710. join('src', 'multiarray', 'abstractdtypes.c'),
  711. join('src', 'multiarray', 'alloc.c'),
  712. join('src', 'multiarray', 'arrayobject.c'),
  713. join('src', 'multiarray', 'arraytypes.c.src'),
  714. join('src', 'multiarray', 'array_coercion.c'),
  715. join('src', 'multiarray', 'array_method.c'),
  716. join('src', 'multiarray', 'array_assign_scalar.c'),
  717. join('src', 'multiarray', 'array_assign_array.c'),
  718. join('src', 'multiarray', 'arrayfunction_override.c'),
  719. join('src', 'multiarray', 'buffer.c'),
  720. join('src', 'multiarray', 'calculation.c'),
  721. join('src', 'multiarray', 'compiled_base.c'),
  722. join('src', 'multiarray', 'common.c'),
  723. join('src', 'multiarray', 'convert.c'),
  724. join('src', 'multiarray', 'convert_datatype.c'),
  725. join('src', 'multiarray', 'conversion_utils.c'),
  726. join('src', 'multiarray', 'ctors.c'),
  727. join('src', 'multiarray', 'datetime.c'),
  728. join('src', 'multiarray', 'datetime_strings.c'),
  729. join('src', 'multiarray', 'datetime_busday.c'),
  730. join('src', 'multiarray', 'datetime_busdaycal.c'),
  731. join('src', 'multiarray', 'descriptor.c'),
  732. join('src', 'multiarray', 'dtypemeta.c'),
  733. join('src', 'multiarray', 'dragon4.c'),
  734. join('src', 'multiarray', 'dtype_transfer.c'),
  735. join('src', 'multiarray', 'einsum.c.src'),
  736. join('src', 'multiarray', 'einsum_sumprod.c.src'),
  737. join('src', 'multiarray', 'flagsobject.c'),
  738. join('src', 'multiarray', 'getset.c'),
  739. join('src', 'multiarray', 'hashdescr.c'),
  740. join('src', 'multiarray', 'item_selection.c'),
  741. join('src', 'multiarray', 'iterators.c'),
  742. join('src', 'multiarray', 'legacy_dtype_implementation.c'),
  743. join('src', 'multiarray', 'lowlevel_strided_loops.c.src'),
  744. join('src', 'multiarray', 'mapping.c'),
  745. join('src', 'multiarray', 'methods.c'),
  746. join('src', 'multiarray', 'multiarraymodule.c'),
  747. join('src', 'multiarray', 'nditer_templ.c.src'),
  748. join('src', 'multiarray', 'nditer_api.c'),
  749. join('src', 'multiarray', 'nditer_constr.c'),
  750. join('src', 'multiarray', 'nditer_pywrap.c'),
  751. join('src', 'multiarray', 'number.c'),
  752. join('src', 'multiarray', 'refcount.c'),
  753. join('src', 'multiarray', 'sequence.c'),
  754. join('src', 'multiarray', 'shape.c'),
  755. join('src', 'multiarray', 'scalarapi.c'),
  756. join('src', 'multiarray', 'scalartypes.c.src'),
  757. join('src', 'multiarray', 'strfuncs.c'),
  758. join('src', 'multiarray', 'temp_elide.c'),
  759. join('src', 'multiarray', 'typeinfo.c'),
  760. join('src', 'multiarray', 'usertypes.c'),
  761. join('src', 'multiarray', 'vdot.c'),
  762. join('src', 'common', 'npy_sort.h.src'),
  763. join('src', 'npysort', 'quicksort.c.src'),
  764. join('src', 'npysort', 'mergesort.c.src'),
  765. join('src', 'npysort', 'timsort.c.src'),
  766. join('src', 'npysort', 'heapsort.c.src'),
  767. join('src', 'npysort', 'radixsort.c.src'),
  768. join('src', 'common', 'npy_partition.h.src'),
  769. join('src', 'npysort', 'selection.c.src'),
  770. join('src', 'common', 'npy_binsearch.h.src'),
  771. join('src', 'npysort', 'binsearch.c.src'),
  772. ]
  773. #######################################################################
  774. # _multiarray_umath module - umath part #
  775. #######################################################################
  776. def generate_umath_c(ext, build_dir):
  777. target = join(build_dir, header_dir, '__umath_generated.c')
  778. dir = os.path.dirname(target)
  779. if not os.path.exists(dir):
  780. os.makedirs(dir)
  781. script = generate_umath_py
  782. if newer(script, target):
  783. with open(target, 'w') as f:
  784. f.write(generate_umath.make_code(generate_umath.defdict,
  785. generate_umath.__file__))
  786. return []
  787. umath_src = [
  788. join('src', 'umath', 'umathmodule.c'),
  789. join('src', 'umath', 'reduction.c'),
  790. join('src', 'umath', 'funcs.inc.src'),
  791. join('src', 'umath', 'simd.inc.src'),
  792. join('src', 'umath', 'loops.h.src'),
  793. join('src', 'umath', 'loops.c.src'),
  794. join('src', 'umath', 'loops_unary_fp.dispatch.c.src'),
  795. join('src', 'umath', 'matmul.h.src'),
  796. join('src', 'umath', 'matmul.c.src'),
  797. join('src', 'umath', 'clip.h.src'),
  798. join('src', 'umath', 'clip.c.src'),
  799. join('src', 'umath', 'ufunc_object.c'),
  800. join('src', 'umath', 'extobj.c'),
  801. join('src', 'umath', 'scalarmath.c.src'),
  802. join('src', 'umath', 'ufunc_type_resolution.c'),
  803. join('src', 'umath', 'override.c'),
  804. ]
  805. umath_deps = [
  806. generate_umath_py,
  807. join('include', 'numpy', 'npy_math.h'),
  808. join('include', 'numpy', 'halffloat.h'),
  809. join('src', 'multiarray', 'common.h'),
  810. join('src', 'multiarray', 'number.h'),
  811. join('src', 'common', 'templ_common.h.src'),
  812. join('src', 'umath', 'simd.inc.src'),
  813. join('src', 'umath', 'override.h'),
  814. join(codegen_dir, 'generate_ufunc_api.py'),
  815. ]
  816. config.add_extension('_multiarray_umath',
  817. sources=multiarray_src + umath_src +
  818. common_src +
  819. [generate_config_h,
  820. generate_numpyconfig_h,
  821. generate_numpy_api,
  822. join(codegen_dir, 'generate_numpy_api.py'),
  823. join('*.py'),
  824. generate_umath_c,
  825. generate_ufunc_api,
  826. ],
  827. depends=deps + multiarray_deps + umath_deps +
  828. common_deps,
  829. libraries=['npymath'],
  830. extra_info=extra_info)
  831. #######################################################################
  832. # umath_tests module #
  833. #######################################################################
  834. config.add_extension('_umath_tests', sources=[
  835. join('src', 'umath', '_umath_tests.c.src'),
  836. join('src', 'umath', '_umath_tests.dispatch.c'),
  837. join('src', 'common', 'npy_cpu_features.c.src'),
  838. ])
  839. #######################################################################
  840. # custom rational dtype module #
  841. #######################################################################
  842. config.add_extension('_rational_tests',
  843. sources=[join('src', 'umath', '_rational_tests.c.src')])
  844. #######################################################################
  845. # struct_ufunc_test module #
  846. #######################################################################
  847. config.add_extension('_struct_ufunc_tests',
  848. sources=[join('src', 'umath', '_struct_ufunc_tests.c.src')])
  849. #######################################################################
  850. # operand_flag_tests module #
  851. #######################################################################
  852. config.add_extension('_operand_flag_tests',
  853. sources=[join('src', 'umath', '_operand_flag_tests.c.src')])
  854. #######################################################################
  855. # SIMD module #
  856. #######################################################################
  857. config.add_extension('_simd', sources=[
  858. join('src', 'common', 'npy_cpu_features.c.src'),
  859. join('src', '_simd', '_simd.c'),
  860. join('src', '_simd', '_simd_inc.h.src'),
  861. join('src', '_simd', '_simd_data.inc.src'),
  862. join('src', '_simd', '_simd.dispatch.c.src'),
  863. ], depends=[
  864. join('src', 'common', 'npy_cpu_dispatch.h'),
  865. join('src', 'common', 'simd', 'simd.h'),
  866. join('src', '_simd', '_simd.h'),
  867. join('src', '_simd', '_simd_inc.h.src'),
  868. join('src', '_simd', '_simd_data.inc.src'),
  869. join('src', '_simd', '_simd_arg.inc'),
  870. join('src', '_simd', '_simd_convert.inc'),
  871. join('src', '_simd', '_simd_easyintrin.inc'),
  872. join('src', '_simd', '_simd_vector.inc'),
  873. ])
  874. config.add_subpackage('tests')
  875. config.add_data_dir('tests/data')
  876. config.add_data_dir('tests/examples')
  877. config.add_data_files('*.pyi')
  878. config.make_svn_version_py()
  879. return config
  880. if __name__ == '__main__':
  881. from numpy.distutils.core import setup
  882. setup(configuration=configuration)