setup.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. from __future__ import division, print_function
  2. import os
  3. import sys
  4. import pickle
  5. import copy
  6. import warnings
  7. import platform
  8. import textwrap
  9. from os.path import join
  10. from numpy.distutils import log
  11. from distutils.dep_util import newer
  12. from distutils.sysconfig import get_config_var
  13. from numpy._build_utils.apple_accelerate import (
  14. uses_accelerate_framework, get_sgemv_fix
  15. )
  16. from numpy.compat import npy_load_module
  17. from setup_common import *
  18. # Set to True to enable relaxed strides checking. This (mostly) means
  19. # that `strides[dim]` is ignored if `shape[dim] == 1` when setting flags.
  20. NPY_RELAXED_STRIDES_CHECKING = (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', "1") != "0")
  21. # Put NPY_RELAXED_STRIDES_DEBUG=1 in the environment if you want numpy to use a
  22. # bogus value for affected strides in order to help smoke out bad stride usage
  23. # when relaxed stride checking is enabled.
  24. NPY_RELAXED_STRIDES_DEBUG = (os.environ.get('NPY_RELAXED_STRIDES_DEBUG', "0") != "0")
  25. NPY_RELAXED_STRIDES_DEBUG = NPY_RELAXED_STRIDES_DEBUG and NPY_RELAXED_STRIDES_CHECKING
  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(object):
  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, 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. for dec, fn, code, header in OPTIONAL_FUNCTION_ATTRIBUTES_WITH_INTRINSICS:
  150. if config.check_gcc_function_attribute_with_intrinsics(dec, fn, code,
  151. header):
  152. moredefs.append((fname2def(fn), 1))
  153. for fn in OPTIONAL_VARIABLE_ATTRIBUTES:
  154. if config.check_gcc_variable_attribute(fn):
  155. m = fn.replace("(", "_").replace(")", "_")
  156. moredefs.append((fname2def(m), 1))
  157. # C99 functions: float and long double versions
  158. check_funcs(C99_FUNCS_SINGLE)
  159. check_funcs(C99_FUNCS_EXTENDED)
  160. def check_complex(config, mathlibs):
  161. priv = []
  162. pub = []
  163. try:
  164. if os.uname()[0] == "Interix":
  165. warnings.warn("Disabling broken complex support. See #1365", stacklevel=2)
  166. return priv, pub
  167. except Exception:
  168. # os.uname not available on all platforms. blanket except ugly but safe
  169. pass
  170. # Check for complex support
  171. st = config.check_header('complex.h')
  172. if st:
  173. priv.append(('HAVE_COMPLEX_H', 1))
  174. pub.append(('NPY_USE_C99_COMPLEX', 1))
  175. for t in C99_COMPLEX_TYPES:
  176. st = config.check_type(t, headers=["complex.h"])
  177. if st:
  178. pub.append(('NPY_HAVE_%s' % type2def(t), 1))
  179. def check_prec(prec):
  180. flist = [f + prec for f in C99_COMPLEX_FUNCS]
  181. decl = dict([(f, True) for f in flist])
  182. if not config.check_funcs_once(flist, call=decl, decl=decl,
  183. libraries=mathlibs):
  184. for f in flist:
  185. if config.check_func(f, call=True, decl=True,
  186. libraries=mathlibs):
  187. priv.append((fname2def(f), 1))
  188. else:
  189. priv.extend([(fname2def(f), 1) for f in flist])
  190. check_prec('')
  191. check_prec('f')
  192. check_prec('l')
  193. return priv, pub
  194. def check_ieee_macros(config):
  195. priv = []
  196. pub = []
  197. macros = []
  198. def _add_decl(f):
  199. priv.append(fname2def("decl_%s" % f))
  200. pub.append('NPY_%s' % fname2def("decl_%s" % f))
  201. # XXX: hack to circumvent cpp pollution from python: python put its
  202. # config.h in the public namespace, so we have a clash for the common
  203. # functions we test. We remove every function tested by python's
  204. # autoconf, hoping their own test are correct
  205. _macros = ["isnan", "isinf", "signbit", "isfinite"]
  206. for f in _macros:
  207. py_symbol = fname2def("decl_%s" % f)
  208. already_declared = config.check_decl(py_symbol,
  209. headers=["Python.h", "math.h"])
  210. if already_declared:
  211. if config.check_macro_true(py_symbol,
  212. headers=["Python.h", "math.h"]):
  213. pub.append('NPY_%s' % fname2def("decl_%s" % f))
  214. else:
  215. macros.append(f)
  216. # Normally, isnan and isinf are macro (C99), but some platforms only have
  217. # func, or both func and macro version. Check for macro only, and define
  218. # replacement ones if not found.
  219. # Note: including Python.h is necessary because it modifies some math.h
  220. # definitions
  221. for f in macros:
  222. st = config.check_decl(f, headers=["Python.h", "math.h"])
  223. if st:
  224. _add_decl(f)
  225. return priv, pub
  226. def check_types(config_cmd, ext, build_dir):
  227. private_defines = []
  228. public_defines = []
  229. # Expected size (in number of bytes) for each type. This is an
  230. # optimization: those are only hints, and an exhaustive search for the size
  231. # is done if the hints are wrong.
  232. expected = {'short': [2], 'int': [4], 'long': [8, 4],
  233. 'float': [4], 'double': [8], 'long double': [16, 12, 8],
  234. 'Py_intptr_t': [8, 4], 'PY_LONG_LONG': [8], 'long long': [8],
  235. 'off_t': [8, 4]}
  236. # Check we have the python header (-dev* packages on Linux)
  237. result = config_cmd.check_header('Python.h')
  238. if not result:
  239. python = 'python'
  240. if '__pypy__' in sys.builtin_module_names:
  241. python = 'pypy'
  242. raise SystemError(
  243. "Cannot compile 'Python.h'. Perhaps you need to "
  244. "install {0}-dev|{0}-devel.".format(python))
  245. res = config_cmd.check_header("endian.h")
  246. if res:
  247. private_defines.append(('HAVE_ENDIAN_H', 1))
  248. public_defines.append(('NPY_HAVE_ENDIAN_H', 1))
  249. res = config_cmd.check_header("sys/endian.h")
  250. if res:
  251. private_defines.append(('HAVE_SYS_ENDIAN_H', 1))
  252. public_defines.append(('NPY_HAVE_SYS_ENDIAN_H', 1))
  253. # Check basic types sizes
  254. for type in ('short', 'int', 'long'):
  255. res = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers=["Python.h"])
  256. if res:
  257. public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), "SIZEOF_%s" % sym2def(type)))
  258. else:
  259. res = config_cmd.check_type_size(type, expected=expected[type])
  260. if res >= 0:
  261. public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
  262. else:
  263. raise SystemError("Checking sizeof (%s) failed !" % type)
  264. for type in ('float', 'double', 'long double'):
  265. already_declared = config_cmd.check_decl("SIZEOF_%s" % sym2def(type),
  266. headers=["Python.h"])
  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. if not already_declared and not type == 'long double':
  271. private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))
  272. else:
  273. raise SystemError("Checking sizeof (%s) failed !" % type)
  274. # Compute size of corresponding complex type: used to check that our
  275. # definition is binary compatible with C99 complex type (check done at
  276. # build time in npy_common.h)
  277. complex_def = "struct {%s __x; %s __y;}" % (type, type)
  278. res = config_cmd.check_type_size(complex_def,
  279. expected=[2 * x for x in expected[type]])
  280. if res >= 0:
  281. public_defines.append(('NPY_SIZEOF_COMPLEX_%s' % sym2def(type), '%d' % res))
  282. else:
  283. raise SystemError("Checking sizeof (%s) failed !" % complex_def)
  284. for type in ('Py_intptr_t', 'off_t'):
  285. res = config_cmd.check_type_size(type, headers=["Python.h"],
  286. library_dirs=[pythonlib_dir()],
  287. expected=expected[type])
  288. if res >= 0:
  289. private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))
  290. public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
  291. else:
  292. raise SystemError("Checking sizeof (%s) failed !" % type)
  293. # We check declaration AND type because that's how distutils does it.
  294. if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']):
  295. res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'],
  296. library_dirs=[pythonlib_dir()],
  297. expected=expected['PY_LONG_LONG'])
  298. if res >= 0:
  299. private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))
  300. public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))
  301. else:
  302. raise SystemError("Checking sizeof (%s) failed !" % 'PY_LONG_LONG')
  303. res = config_cmd.check_type_size('long long',
  304. expected=expected['long long'])
  305. if res >= 0:
  306. #private_defines.append(('SIZEOF_%s' % sym2def('long long'), '%d' % res))
  307. public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res))
  308. else:
  309. raise SystemError("Checking sizeof (%s) failed !" % 'long long')
  310. if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']):
  311. raise RuntimeError(
  312. "Config wo CHAR_BIT is not supported"
  313. ", please contact the maintainers")
  314. return private_defines, public_defines
  315. def check_mathlib(config_cmd):
  316. # Testing the C math library
  317. mathlibs = []
  318. mathlibs_choices = [[], ['m'], ['cpml']]
  319. mathlib = os.environ.get('MATHLIB')
  320. if mathlib:
  321. mathlibs_choices.insert(0, mathlib.split(','))
  322. for libs in mathlibs_choices:
  323. if config_cmd.check_func("exp", libraries=libs, decl=True, call=True):
  324. mathlibs = libs
  325. break
  326. else:
  327. raise EnvironmentError("math library missing; rerun "
  328. "setup.py after setting the "
  329. "MATHLIB env variable")
  330. return mathlibs
  331. def visibility_define(config):
  332. """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
  333. string)."""
  334. hide = '__attribute__((visibility("hidden")))'
  335. if config.check_gcc_function_attribute(hide, 'hideme'):
  336. return hide
  337. else:
  338. return ''
  339. def configuration(parent_package='',top_path=None):
  340. from numpy.distutils.misc_util import Configuration, dot_join
  341. from numpy.distutils.system_info import get_info, dict_append
  342. config = Configuration('core', parent_package, top_path)
  343. local_dir = config.local_path
  344. codegen_dir = join(local_dir, 'code_generators')
  345. if is_released(config):
  346. warnings.simplefilter('error', MismatchCAPIWarning)
  347. # Check whether we have a mismatch between the set C API VERSION and the
  348. # actual C API VERSION
  349. check_api_version(C_API_VERSION, codegen_dir)
  350. generate_umath_py = join(codegen_dir, 'generate_umath.py')
  351. n = dot_join(config.name, 'generate_umath')
  352. generate_umath = npy_load_module('_'.join(n.split('.')),
  353. generate_umath_py, ('.py', 'U', 1))
  354. header_dir = 'include/numpy' # this is relative to config.path_in_package
  355. cocache = CallOnceOnly()
  356. def generate_config_h(ext, build_dir):
  357. target = join(build_dir, header_dir, 'config.h')
  358. d = os.path.dirname(target)
  359. if not os.path.exists(d):
  360. os.makedirs(d)
  361. if newer(__file__, target):
  362. config_cmd = config.get_config_cmd()
  363. log.info('Generating %s', target)
  364. # Check sizeof
  365. moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir)
  366. # Check math library and C99 math funcs availability
  367. mathlibs = check_mathlib(config_cmd)
  368. moredefs.append(('MATHLIB', ','.join(mathlibs)))
  369. check_math_capabilities(config_cmd, moredefs, mathlibs)
  370. moredefs.extend(cocache.check_ieee_macros(config_cmd)[0])
  371. moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[0])
  372. # Signal check
  373. if is_npy_no_signal():
  374. moredefs.append('__NPY_PRIVATE_NO_SIGNAL')
  375. # Windows checks
  376. if sys.platform == 'win32' or os.name == 'nt':
  377. win32_checks(moredefs)
  378. # C99 restrict keyword
  379. moredefs.append(('NPY_RESTRICT', config_cmd.check_restrict()))
  380. # Inline check
  381. inline = config_cmd.check_inline()
  382. # Use relaxed stride checking
  383. if NPY_RELAXED_STRIDES_CHECKING:
  384. moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1))
  385. # Use bogus stride debug aid when relaxed strides are enabled
  386. if NPY_RELAXED_STRIDES_DEBUG:
  387. moredefs.append(('NPY_RELAXED_STRIDES_DEBUG', 1))
  388. # Get long double representation
  389. rep = check_long_double_representation(config_cmd)
  390. moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1))
  391. if check_for_right_shift_internal_compiler_error(config_cmd):
  392. moredefs.append('NPY_DO_NOT_OPTIMIZE_LONG_right_shift')
  393. moredefs.append('NPY_DO_NOT_OPTIMIZE_ULONG_right_shift')
  394. moredefs.append('NPY_DO_NOT_OPTIMIZE_LONGLONG_right_shift')
  395. moredefs.append('NPY_DO_NOT_OPTIMIZE_ULONGLONG_right_shift')
  396. # Py3K check
  397. if sys.version_info[0] >= 3:
  398. moredefs.append(('NPY_PY3K', 1))
  399. # Generate the config.h file from moredefs
  400. with open(target, 'w') as target_f:
  401. for d in moredefs:
  402. if isinstance(d, str):
  403. target_f.write('#define %s\n' % (d))
  404. else:
  405. target_f.write('#define %s %s\n' % (d[0], d[1]))
  406. # define inline to our keyword, or nothing
  407. target_f.write('#ifndef __cplusplus\n')
  408. if inline == 'inline':
  409. target_f.write('/* #undef inline */\n')
  410. else:
  411. target_f.write('#define inline %s\n' % inline)
  412. target_f.write('#endif\n')
  413. # add the guard to make sure config.h is never included directly,
  414. # but always through npy_config.h
  415. target_f.write(textwrap.dedent("""
  416. #ifndef _NPY_NPY_CONFIG_H_
  417. #error config.h should never be included directly, include npy_config.h instead
  418. #endif
  419. """))
  420. log.info('File: %s' % target)
  421. with open(target) as target_f:
  422. log.info(target_f.read())
  423. log.info('EOF')
  424. else:
  425. mathlibs = []
  426. with open(target) as target_f:
  427. for line in target_f:
  428. s = '#define MATHLIB'
  429. if line.startswith(s):
  430. value = line[len(s):].strip()
  431. if value:
  432. mathlibs.extend(value.split(','))
  433. # Ugly: this can be called within a library and not an extension,
  434. # in which case there is no libraries attributes (and none is
  435. # needed).
  436. if hasattr(ext, 'libraries'):
  437. ext.libraries.extend(mathlibs)
  438. incl_dir = os.path.dirname(target)
  439. if incl_dir not in config.numpy_include_dirs:
  440. config.numpy_include_dirs.append(incl_dir)
  441. return target
  442. def generate_numpyconfig_h(ext, build_dir):
  443. """Depends on config.h: generate_config_h has to be called before !"""
  444. # put common include directory in build_dir on search path
  445. # allows using code generation in headers headers
  446. config.add_include_dirs(join(build_dir, "src", "common"))
  447. config.add_include_dirs(join(build_dir, "src", "npymath"))
  448. target = join(build_dir, header_dir, '_numpyconfig.h')
  449. d = os.path.dirname(target)
  450. if not os.path.exists(d):
  451. os.makedirs(d)
  452. if newer(__file__, target):
  453. config_cmd = config.get_config_cmd()
  454. log.info('Generating %s', target)
  455. # Check sizeof
  456. ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir)
  457. if is_npy_no_signal():
  458. moredefs.append(('NPY_NO_SIGNAL', 1))
  459. if is_npy_no_smp():
  460. moredefs.append(('NPY_NO_SMP', 1))
  461. else:
  462. moredefs.append(('NPY_NO_SMP', 0))
  463. mathlibs = check_mathlib(config_cmd)
  464. moredefs.extend(cocache.check_ieee_macros(config_cmd)[1])
  465. moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[1])
  466. if NPY_RELAXED_STRIDES_CHECKING:
  467. moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1))
  468. if NPY_RELAXED_STRIDES_DEBUG:
  469. moredefs.append(('NPY_RELAXED_STRIDES_DEBUG', 1))
  470. # Check whether we can use inttypes (C99) formats
  471. if config_cmd.check_decl('PRIdPTR', headers=['inttypes.h']):
  472. moredefs.append(('NPY_USE_C99_FORMATS', 1))
  473. # visibility check
  474. hidden_visibility = visibility_define(config_cmd)
  475. moredefs.append(('NPY_VISIBILITY_HIDDEN', hidden_visibility))
  476. # Add the C API/ABI versions
  477. moredefs.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION))
  478. moredefs.append(('NPY_API_VERSION', '0x%.8X' % C_API_VERSION))
  479. # Add moredefs to header
  480. with open(target, 'w') as target_f:
  481. for d in moredefs:
  482. if isinstance(d, str):
  483. target_f.write('#define %s\n' % (d))
  484. else:
  485. target_f.write('#define %s %s\n' % (d[0], d[1]))
  486. # Define __STDC_FORMAT_MACROS
  487. target_f.write(textwrap.dedent("""
  488. #ifndef __STDC_FORMAT_MACROS
  489. #define __STDC_FORMAT_MACROS 1
  490. #endif
  491. """))
  492. # Dump the numpyconfig.h header to stdout
  493. log.info('File: %s' % target)
  494. with open(target) as target_f:
  495. log.info(target_f.read())
  496. log.info('EOF')
  497. config.add_data_files((header_dir, target))
  498. return target
  499. def generate_api_func(module_name):
  500. def generate_api(ext, build_dir):
  501. script = join(codegen_dir, module_name + '.py')
  502. sys.path.insert(0, codegen_dir)
  503. try:
  504. m = __import__(module_name)
  505. log.info('executing %s', script)
  506. h_file, c_file, doc_file = m.generate_api(os.path.join(build_dir, header_dir))
  507. finally:
  508. del sys.path[0]
  509. config.add_data_files((header_dir, h_file),
  510. (header_dir, doc_file))
  511. return (h_file,)
  512. return generate_api
  513. generate_numpy_api = generate_api_func('generate_numpy_api')
  514. generate_ufunc_api = generate_api_func('generate_ufunc_api')
  515. config.add_include_dirs(join(local_dir, "src", "common"))
  516. config.add_include_dirs(join(local_dir, "src"))
  517. config.add_include_dirs(join(local_dir))
  518. config.add_data_dir('include/numpy')
  519. config.add_include_dirs(join('src', 'npymath'))
  520. config.add_include_dirs(join('src', 'multiarray'))
  521. config.add_include_dirs(join('src', 'umath'))
  522. config.add_include_dirs(join('src', 'npysort'))
  523. config.add_define_macros([("NPY_INTERNAL_BUILD", "1")]) # this macro indicates that Numpy build is in process
  524. config.add_define_macros([("HAVE_NPY_CONFIG_H", "1")])
  525. if sys.platform[:3] == "aix":
  526. config.add_define_macros([("_LARGE_FILES", None)])
  527. else:
  528. config.add_define_macros([("_FILE_OFFSET_BITS", "64")])
  529. config.add_define_macros([('_LARGEFILE_SOURCE', '1')])
  530. config.add_define_macros([('_LARGEFILE64_SOURCE', '1')])
  531. config.numpy_include_dirs.extend(config.paths('include'))
  532. deps = [join('src', 'npymath', '_signbit.c'),
  533. join('include', 'numpy', '*object.h'),
  534. join(codegen_dir, 'genapi.py'),
  535. ]
  536. #######################################################################
  537. # npymath library #
  538. #######################################################################
  539. subst_dict = dict([("sep", os.path.sep), ("pkgname", "numpy.core")])
  540. def get_mathlib_info(*args):
  541. # Another ugly hack: the mathlib info is known once build_src is run,
  542. # but we cannot use add_installed_pkg_config here either, so we only
  543. # update the substitution dictionary during npymath build
  544. config_cmd = config.get_config_cmd()
  545. # Check that the toolchain works, to fail early if it doesn't
  546. # (avoid late errors with MATHLIB which are confusing if the
  547. # compiler does not work).
  548. st = config_cmd.try_link('int main(void) { return 0;}')
  549. if not st:
  550. # rerun the failing command in verbose mode
  551. config_cmd.compiler.verbose = True
  552. config_cmd.try_link('int main(void) { return 0;}')
  553. raise RuntimeError("Broken toolchain: cannot link a simple C program")
  554. mlibs = check_mathlib(config_cmd)
  555. posix_mlib = ' '.join(['-l%s' % l for l in mlibs])
  556. msvc_mlib = ' '.join(['%s.lib' % l for l in mlibs])
  557. subst_dict["posix_mathlib"] = posix_mlib
  558. subst_dict["msvc_mathlib"] = msvc_mlib
  559. npymath_sources = [join('src', 'npymath', 'npy_math_internal.h.src'),
  560. join('src', 'npymath', 'npy_math.c'),
  561. join('src', 'npymath', 'ieee754.c.src'),
  562. join('src', 'npymath', 'npy_math_complex.c.src'),
  563. join('src', 'npymath', 'halffloat.c')
  564. ]
  565. # Must be true for CRT compilers but not MinGW/cygwin. See gh-9977.
  566. # Intel and Clang also don't seem happy with /GL
  567. is_msvc = (platform.platform().startswith('Windows') and
  568. platform.python_compiler().startswith('MS'))
  569. config.add_installed_library('npymath',
  570. sources=npymath_sources + [get_mathlib_info],
  571. install_dir='lib',
  572. build_info={
  573. 'include_dirs' : [], # empty list required for creating npy_math_internal.h
  574. 'extra_compiler_args' : (['/GL-'] if is_msvc else []),
  575. })
  576. config.add_npy_pkg_config("npymath.ini.in", "lib/npy-pkg-config",
  577. subst_dict)
  578. config.add_npy_pkg_config("mlib.ini.in", "lib/npy-pkg-config",
  579. subst_dict)
  580. #######################################################################
  581. # npysort library #
  582. #######################################################################
  583. # This library is created for the build but it is not installed
  584. npysort_sources = [join('src', 'common', 'npy_sort.h.src'),
  585. join('src', 'npysort', 'quicksort.c.src'),
  586. join('src', 'npysort', 'mergesort.c.src'),
  587. join('src', 'npysort', 'timsort.c.src'),
  588. join('src', 'npysort', 'heapsort.c.src'),
  589. join('src', 'npysort', 'radixsort.c.src'),
  590. join('src', 'common', 'npy_partition.h.src'),
  591. join('src', 'npysort', 'selection.c.src'),
  592. join('src', 'common', 'npy_binsearch.h.src'),
  593. join('src', 'npysort', 'binsearch.c.src'),
  594. ]
  595. config.add_library('npysort',
  596. sources=npysort_sources,
  597. include_dirs=[])
  598. #######################################################################
  599. # multiarray_tests module #
  600. #######################################################################
  601. config.add_extension('_multiarray_tests',
  602. sources=[join('src', 'multiarray', '_multiarray_tests.c.src'),
  603. join('src', 'common', 'mem_overlap.c')],
  604. depends=[join('src', 'common', 'mem_overlap.h'),
  605. join('src', 'common', 'npy_extint128.h')],
  606. libraries=['npymath'])
  607. #######################################################################
  608. # _multiarray_umath module - common part #
  609. #######################################################################
  610. common_deps = [
  611. join('src', 'common', 'array_assign.h'),
  612. join('src', 'common', 'binop_override.h'),
  613. join('src', 'common', 'cblasfuncs.h'),
  614. join('src', 'common', 'lowlevel_strided_loops.h'),
  615. join('src', 'common', 'mem_overlap.h'),
  616. join('src', 'common', 'npy_cblas.h'),
  617. join('src', 'common', 'npy_config.h'),
  618. join('src', 'common', 'npy_ctypes.h'),
  619. join('src', 'common', 'npy_extint128.h'),
  620. join('src', 'common', 'npy_import.h'),
  621. join('src', 'common', 'npy_longdouble.h'),
  622. join('src', 'common', 'templ_common.h.src'),
  623. join('src', 'common', 'ucsnarrow.h'),
  624. join('src', 'common', 'ufunc_override.h'),
  625. join('src', 'common', 'umathmodule.h'),
  626. join('src', 'common', 'numpyos.h'),
  627. ]
  628. common_src = [
  629. join('src', 'common', 'array_assign.c'),
  630. join('src', 'common', 'mem_overlap.c'),
  631. join('src', 'common', 'npy_longdouble.c'),
  632. join('src', 'common', 'templ_common.h.src'),
  633. join('src', 'common', 'ucsnarrow.c'),
  634. join('src', 'common', 'ufunc_override.c'),
  635. join('src', 'common', 'numpyos.c'),
  636. ]
  637. if os.environ.get('NPY_USE_BLAS_ILP64', "0") != "0":
  638. blas_info = get_info('blas_ilp64_opt', 2)
  639. else:
  640. blas_info = get_info('blas_opt', 0)
  641. have_blas = blas_info and ('HAVE_CBLAS', None) in blas_info.get('define_macros', [])
  642. if have_blas:
  643. extra_info = blas_info
  644. # These files are also in MANIFEST.in so that they are always in
  645. # the source distribution independently of HAVE_CBLAS.
  646. common_src.extend([join('src', 'common', 'cblasfuncs.c'),
  647. join('src', 'common', 'python_xerbla.c'),
  648. ])
  649. if uses_accelerate_framework(blas_info):
  650. common_src.extend(get_sgemv_fix())
  651. else:
  652. extra_info = {}
  653. #######################################################################
  654. # _multiarray_umath module - multiarray part #
  655. #######################################################################
  656. multiarray_deps = [
  657. join('src', 'multiarray', 'arrayobject.h'),
  658. join('src', 'multiarray', 'arraytypes.h'),
  659. join('src', 'multiarray', 'arrayfunction_override.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', 'dragon4.h'),
  669. join('src', 'multiarray', 'getset.h'),
  670. join('src', 'multiarray', 'hashdescr.h'),
  671. join('src', 'multiarray', 'iterators.h'),
  672. join('src', 'multiarray', 'mapping.h'),
  673. join('src', 'multiarray', 'methods.h'),
  674. join('src', 'multiarray', 'multiarraymodule.h'),
  675. join('src', 'multiarray', 'nditer_impl.h'),
  676. join('src', 'multiarray', 'number.h'),
  677. join('src', 'multiarray', 'refcount.h'),
  678. join('src', 'multiarray', 'scalartypes.h'),
  679. join('src', 'multiarray', 'sequence.h'),
  680. join('src', 'multiarray', 'shape.h'),
  681. join('src', 'multiarray', 'strfuncs.h'),
  682. join('src', 'multiarray', 'typeinfo.h'),
  683. join('src', 'multiarray', 'usertypes.h'),
  684. join('src', 'multiarray', 'vdot.h'),
  685. join('include', 'numpy', 'arrayobject.h'),
  686. join('include', 'numpy', '_neighborhood_iterator_imp.h'),
  687. join('include', 'numpy', 'npy_endian.h'),
  688. join('include', 'numpy', 'arrayscalars.h'),
  689. join('include', 'numpy', 'noprefix.h'),
  690. join('include', 'numpy', 'npy_interrupt.h'),
  691. join('include', 'numpy', 'npy_3kcompat.h'),
  692. join('include', 'numpy', 'npy_math.h'),
  693. join('include', 'numpy', 'halffloat.h'),
  694. join('include', 'numpy', 'npy_common.h'),
  695. join('include', 'numpy', 'npy_os.h'),
  696. join('include', 'numpy', 'utils.h'),
  697. join('include', 'numpy', 'ndarrayobject.h'),
  698. join('include', 'numpy', 'npy_cpu.h'),
  699. join('include', 'numpy', 'numpyconfig.h'),
  700. join('include', 'numpy', 'ndarraytypes.h'),
  701. join('include', 'numpy', 'npy_1_7_deprecated_api.h'),
  702. # add library sources as distuils does not consider libraries
  703. # dependencies
  704. ] + npysort_sources + npymath_sources
  705. multiarray_src = [
  706. join('src', 'multiarray', 'alloc.c'),
  707. join('src', 'multiarray', 'arrayobject.c'),
  708. join('src', 'multiarray', 'arraytypes.c.src'),
  709. join('src', 'multiarray', 'array_assign_scalar.c'),
  710. join('src', 'multiarray', 'array_assign_array.c'),
  711. join('src', 'multiarray', 'arrayfunction_override.c'),
  712. join('src', 'multiarray', 'buffer.c'),
  713. join('src', 'multiarray', 'calculation.c'),
  714. join('src', 'multiarray', 'compiled_base.c'),
  715. join('src', 'multiarray', 'common.c'),
  716. join('src', 'multiarray', 'convert.c'),
  717. join('src', 'multiarray', 'convert_datatype.c'),
  718. join('src', 'multiarray', 'conversion_utils.c'),
  719. join('src', 'multiarray', 'ctors.c'),
  720. join('src', 'multiarray', 'datetime.c'),
  721. join('src', 'multiarray', 'datetime_strings.c'),
  722. join('src', 'multiarray', 'datetime_busday.c'),
  723. join('src', 'multiarray', 'datetime_busdaycal.c'),
  724. join('src', 'multiarray', 'descriptor.c'),
  725. join('src', 'multiarray', 'dragon4.c'),
  726. join('src', 'multiarray', 'dtype_transfer.c'),
  727. join('src', 'multiarray', 'einsum.c.src'),
  728. join('src', 'multiarray', 'flagsobject.c'),
  729. join('src', 'multiarray', 'getset.c'),
  730. join('src', 'multiarray', 'hashdescr.c'),
  731. join('src', 'multiarray', 'item_selection.c'),
  732. join('src', 'multiarray', 'iterators.c'),
  733. join('src', 'multiarray', 'lowlevel_strided_loops.c.src'),
  734. join('src', 'multiarray', 'mapping.c'),
  735. join('src', 'multiarray', 'methods.c'),
  736. join('src', 'multiarray', 'multiarraymodule.c'),
  737. join('src', 'multiarray', 'nditer_templ.c.src'),
  738. join('src', 'multiarray', 'nditer_api.c'),
  739. join('src', 'multiarray', 'nditer_constr.c'),
  740. join('src', 'multiarray', 'nditer_pywrap.c'),
  741. join('src', 'multiarray', 'number.c'),
  742. join('src', 'multiarray', 'refcount.c'),
  743. join('src', 'multiarray', 'sequence.c'),
  744. join('src', 'multiarray', 'shape.c'),
  745. join('src', 'multiarray', 'scalarapi.c'),
  746. join('src', 'multiarray', 'scalartypes.c.src'),
  747. join('src', 'multiarray', 'strfuncs.c'),
  748. join('src', 'multiarray', 'temp_elide.c'),
  749. join('src', 'multiarray', 'typeinfo.c'),
  750. join('src', 'multiarray', 'usertypes.c'),
  751. join('src', 'multiarray', 'vdot.c'),
  752. ]
  753. #######################################################################
  754. # _multiarray_umath module - umath part #
  755. #######################################################################
  756. def generate_umath_c(ext, build_dir):
  757. target = join(build_dir, header_dir, '__umath_generated.c')
  758. dir = os.path.dirname(target)
  759. if not os.path.exists(dir):
  760. os.makedirs(dir)
  761. script = generate_umath_py
  762. if newer(script, target):
  763. with open(target, 'w') as f:
  764. f.write(generate_umath.make_code(generate_umath.defdict,
  765. generate_umath.__file__))
  766. return []
  767. umath_src = [
  768. join('src', 'umath', 'umathmodule.c'),
  769. join('src', 'umath', 'reduction.c'),
  770. join('src', 'umath', 'funcs.inc.src'),
  771. join('src', 'umath', 'simd.inc.src'),
  772. join('src', 'umath', 'loops.h.src'),
  773. join('src', 'umath', 'loops.c.src'),
  774. join('src', 'umath', 'matmul.h.src'),
  775. join('src', 'umath', 'matmul.c.src'),
  776. join('src', 'umath', 'clip.h.src'),
  777. join('src', 'umath', 'clip.c.src'),
  778. join('src', 'umath', 'ufunc_object.c'),
  779. join('src', 'umath', 'extobj.c'),
  780. join('src', 'umath', 'cpuid.c'),
  781. join('src', 'umath', 'scalarmath.c.src'),
  782. join('src', 'umath', 'ufunc_type_resolution.c'),
  783. join('src', 'umath', 'override.c'),
  784. ]
  785. umath_deps = [
  786. generate_umath_py,
  787. join('include', 'numpy', 'npy_math.h'),
  788. join('include', 'numpy', 'halffloat.h'),
  789. join('src', 'multiarray', 'common.h'),
  790. join('src', 'multiarray', 'number.h'),
  791. join('src', 'common', 'templ_common.h.src'),
  792. join('src', 'umath', 'simd.inc.src'),
  793. join('src', 'umath', 'override.h'),
  794. join(codegen_dir, 'generate_ufunc_api.py'),
  795. ]
  796. config.add_extension('_multiarray_umath',
  797. sources=multiarray_src + umath_src +
  798. npymath_sources + common_src +
  799. [generate_config_h,
  800. generate_numpyconfig_h,
  801. generate_numpy_api,
  802. join(codegen_dir, 'generate_numpy_api.py'),
  803. join('*.py'),
  804. generate_umath_c,
  805. generate_ufunc_api,
  806. ],
  807. depends=deps + multiarray_deps + umath_deps +
  808. common_deps,
  809. libraries=['npymath', 'npysort'],
  810. extra_info=extra_info)
  811. #######################################################################
  812. # umath_tests module #
  813. #######################################################################
  814. config.add_extension('_umath_tests',
  815. sources=[join('src', 'umath', '_umath_tests.c.src')])
  816. #######################################################################
  817. # custom rational dtype module #
  818. #######################################################################
  819. config.add_extension('_rational_tests',
  820. sources=[join('src', 'umath', '_rational_tests.c.src')])
  821. #######################################################################
  822. # struct_ufunc_test module #
  823. #######################################################################
  824. config.add_extension('_struct_ufunc_tests',
  825. sources=[join('src', 'umath', '_struct_ufunc_tests.c.src')])
  826. #######################################################################
  827. # operand_flag_tests module #
  828. #######################################################################
  829. config.add_extension('_operand_flag_tests',
  830. sources=[join('src', 'umath', '_operand_flag_tests.c.src')])
  831. config.add_data_dir('tests')
  832. config.add_data_dir('tests/data')
  833. config.make_svn_version_py()
  834. return config
  835. if __name__ == '__main__':
  836. from numpy.distutils.core import setup
  837. setup(configuration=configuration)