setup.py 41 KB

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