__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. """
  2. NumPy
  3. =====
  4. Provides
  5. 1. An array object of arbitrary homogeneous items
  6. 2. Fast mathematical operations over arrays
  7. 3. Linear Algebra, Fourier Transforms, Random Number Generation
  8. How to use the documentation
  9. ----------------------------
  10. Documentation is available in two forms: docstrings provided
  11. with the code, and a loose standing reference guide, available from
  12. `the NumPy homepage <https://www.scipy.org>`_.
  13. We recommend exploring the docstrings using
  14. `IPython <https://ipython.org>`_, an advanced Python shell with
  15. TAB-completion and introspection capabilities. See below for further
  16. instructions.
  17. The docstring examples assume that `numpy` has been imported as `np`::
  18. >>> import numpy as np
  19. Code snippets are indicated by three greater-than signs::
  20. >>> x = 42
  21. >>> x = x + 1
  22. Use the built-in ``help`` function to view a function's docstring::
  23. >>> help(np.sort)
  24. ... # doctest: +SKIP
  25. For some objects, ``np.info(obj)`` may provide additional help. This is
  26. particularly true if you see the line "Help on ufunc object:" at the top
  27. of the help() page. Ufuncs are implemented in C, not Python, for speed.
  28. The native Python help() does not know how to view their help, but our
  29. np.info() function does.
  30. To search for documents containing a keyword, do::
  31. >>> np.lookfor('keyword')
  32. ... # doctest: +SKIP
  33. General-purpose documents like a glossary and help on the basic concepts
  34. of numpy are available under the ``doc`` sub-module::
  35. >>> from numpy import doc
  36. >>> help(doc)
  37. ... # doctest: +SKIP
  38. Available subpackages
  39. ---------------------
  40. doc
  41. Topical documentation on broadcasting, indexing, etc.
  42. lib
  43. Basic functions used by several sub-packages.
  44. random
  45. Core Random Tools
  46. linalg
  47. Core Linear Algebra Tools
  48. fft
  49. Core FFT routines
  50. polynomial
  51. Polynomial tools
  52. testing
  53. NumPy testing tools
  54. f2py
  55. Fortran to Python Interface Generator.
  56. distutils
  57. Enhancements to distutils with support for
  58. Fortran compilers support and more.
  59. Utilities
  60. ---------
  61. test
  62. Run numpy unittests
  63. show_config
  64. Show numpy build configuration
  65. dual
  66. Overwrite certain functions with high-performance Scipy tools
  67. matlib
  68. Make everything matrices.
  69. __version__
  70. NumPy version string
  71. Viewing documentation using IPython
  72. -----------------------------------
  73. Start IPython with the NumPy profile (``ipython -p numpy``), which will
  74. import `numpy` under the alias `np`. Then, use the ``cpaste`` command to
  75. paste examples into the shell. To see which functions are available in
  76. `numpy`, type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
  77. ``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
  78. down the list. To view the docstring for a function, use
  79. ``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
  80. the source code).
  81. Copies vs. in-place operation
  82. -----------------------------
  83. Most of the functions in `numpy` return a copy of the array argument
  84. (e.g., `np.sort`). In-place versions of these functions are often
  85. available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
  86. Exceptions to this rule are documented.
  87. """
  88. import sys
  89. import warnings
  90. from ._globals import ModuleDeprecationWarning, VisibleDeprecationWarning
  91. from ._globals import _NoValue
  92. # We first need to detect if we're being called as part of the numpy setup
  93. # procedure itself in a reliable manner.
  94. try:
  95. __NUMPY_SETUP__
  96. except NameError:
  97. __NUMPY_SETUP__ = False
  98. if __NUMPY_SETUP__:
  99. sys.stderr.write('Running from numpy source directory.\n')
  100. else:
  101. try:
  102. from numpy.__config__ import show as show_config
  103. except ImportError:
  104. msg = """Error importing numpy: you should not try to import numpy from
  105. its source directory; please exit the numpy source tree, and relaunch
  106. your python interpreter from there."""
  107. raise ImportError(msg)
  108. from .version import git_revision as __git_revision__
  109. from .version import version as __version__
  110. __all__ = ['ModuleDeprecationWarning',
  111. 'VisibleDeprecationWarning']
  112. # Allow distributors to run custom init code
  113. from . import _distributor_init
  114. from . import core
  115. from .core import *
  116. from . import compat
  117. from . import lib
  118. # NOTE: to be revisited following future namespace cleanup.
  119. # See gh-14454 and gh-15672 for discussion.
  120. from .lib import *
  121. from . import linalg
  122. from . import fft
  123. from . import polynomial
  124. from . import random
  125. from . import ctypeslib
  126. from . import ma
  127. from . import matrixlib as _mat
  128. from .matrixlib import *
  129. # Make these accessible from numpy name-space
  130. # but not imported in from numpy import *
  131. # TODO[gh-6103]: Deprecate these
  132. from builtins import bool, int, float, complex, object, str
  133. from .compat import long, unicode
  134. from .core import round, abs, max, min
  135. # now that numpy modules are imported, can initialize limits
  136. core.getlimits._register_known_types()
  137. __all__.extend(['__version__', 'show_config'])
  138. __all__.extend(core.__all__)
  139. __all__.extend(_mat.__all__)
  140. __all__.extend(lib.__all__)
  141. __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
  142. # These are added by `from .core import *` and `core.__all__`, but we
  143. # overwrite them above with builtins we do _not_ want to export.
  144. __all__.remove('long')
  145. __all__.remove('unicode')
  146. # Remove things that are in the numpy.lib but not in the numpy namespace
  147. # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
  148. # that prevents adding more things to the main namespace by accident.
  149. # The list below will grow until the `from .lib import *` fixme above is
  150. # taken care of
  151. __all__.remove('Arrayterator')
  152. del Arrayterator
  153. # Filter out Cython harmless warnings
  154. warnings.filterwarnings("ignore", message="numpy.dtype size changed")
  155. warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
  156. warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
  157. # oldnumeric and numarray were removed in 1.9. In case some packages import
  158. # but do not use them, we define them here for backward compatibility.
  159. oldnumeric = 'removed'
  160. numarray = 'removed'
  161. if sys.version_info[:2] >= (3, 7):
  162. # Importing Tester requires importing all of UnitTest which is not a
  163. # cheap import Since it is mainly used in test suits, we lazy import it
  164. # here to save on the order of 10 ms of import time for most users
  165. #
  166. # The previous way Tester was imported also had a side effect of adding
  167. # the full `numpy.testing` namespace
  168. #
  169. # module level getattr is only supported in 3.7 onwards
  170. # https://www.python.org/dev/peps/pep-0562/
  171. def __getattr__(attr):
  172. if attr == 'testing':
  173. import numpy.testing as testing
  174. return testing
  175. elif attr == 'Tester':
  176. from .testing import Tester
  177. return Tester
  178. else:
  179. raise AttributeError("module {!r} has no attribute "
  180. "{!r}".format(__name__, attr))
  181. def __dir__():
  182. return list(globals().keys() | {'Tester', 'testing'})
  183. else:
  184. # We don't actually use this ourselves anymore, but I'm not 100% sure that
  185. # no-one else in the world is using it (though I hope not)
  186. from .testing import Tester
  187. # Pytest testing
  188. from numpy._pytesttester import PytestTester
  189. test = PytestTester(__name__)
  190. del PytestTester
  191. def _sanity_check():
  192. """
  193. Quick sanity checks for common bugs caused by environment.
  194. There are some cases e.g. with wrong BLAS ABI that cause wrong
  195. results under specific runtime conditions that are not necessarily
  196. achieved during test suite runs, and it is useful to catch those early.
  197. See https://github.com/numpy/numpy/issues/8577 and other
  198. similar bug reports.
  199. """
  200. try:
  201. x = ones(2, dtype=float32)
  202. if not abs(x.dot(x) - 2.0) < 1e-5:
  203. raise AssertionError()
  204. except AssertionError:
  205. msg = ("The current Numpy installation ({!r}) fails to "
  206. "pass simple sanity checks. This can be caused for example "
  207. "by incorrect BLAS library being linked in, or by mixing "
  208. "package managers (pip, conda, apt, ...). Search closed "
  209. "numpy issues for similar problems.")
  210. raise RuntimeError(msg.format(__file__))
  211. _sanity_check()
  212. del _sanity_check
  213. def _mac_os_check():
  214. """
  215. Quick Sanity check for Mac OS look for accelerate build bugs.
  216. Testing numpy polyfit calls init_dgelsd(LAPACK)
  217. """
  218. try:
  219. c = array([3., 2., 1.])
  220. x = linspace(0, 2, 5)
  221. y = polyval(c, x)
  222. _ = polyfit(x, y, 2, cov=True)
  223. except ValueError:
  224. pass
  225. import sys
  226. if sys.platform == "darwin":
  227. with warnings.catch_warnings(record=True) as w:
  228. _mac_os_check()
  229. # Throw runtime error, if the test failed Check for warning and error_message
  230. error_message = ""
  231. if len(w) > 0:
  232. error_message = "{}: {}".format(w[-1].category.__name__, str(w[-1].message))
  233. msg = (
  234. "Polyfit sanity test emitted a warning, most likely due "
  235. "to using a buggy Accelerate backend. "
  236. "If you compiled yourself, "
  237. "see site.cfg.example for information. "
  238. "Otherwise report this to the vendor "
  239. "that provided NumPy.\n{}\n".format(
  240. error_message))
  241. raise RuntimeError(msg)
  242. del _mac_os_check
  243. def _win_os_check():
  244. """
  245. Quick Sanity check for Windows OS: look for fmod bug issue 16744.
  246.  """
  247. try:
  248. a = arange(13 * 13, dtype= float64).reshape(13, 13)
  249. a = a % 17 # calls fmod
  250. linalg.eig(a)
  251. except Exception:
  252. msg = ("The current Numpy installation ({!r}) fails to "
  253. "pass a sanity check due to a bug in the windows runtime. "
  254. "See this issue for more information: "
  255. "https://tinyurl.com/y3dm3h86")
  256. raise RuntimeError(msg.format(__file__)) from None
  257. if sys.platform == "win32" and sys.maxsize > 2**32:
  258. _win_os_check()
  259. del _win_os_check
  260. # We usually use madvise hugepages support, but on some old kernels it
  261. # is slow and thus better avoided.
  262. # Specifically kernel version 4.6 had a bug fix which probably fixed this:
  263. # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
  264. import os
  265. use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
  266. if sys.platform == "linux" and use_hugepage is None:
  267. # If there is an issue with parsing the kernel version,
  268. # set use_hugepages to 0. Usage of LooseVersion will handle
  269. # the kernel version parsing better, but avoided since it
  270. # will increase the import time. See: #16679 for related discussion.
  271. try:
  272. use_hugepage = 1
  273. kernel_version = os.uname().release.split(".")[:2]
  274. kernel_version = tuple(int(v) for v in kernel_version)
  275. if kernel_version < (4, 6):
  276. use_hugepage = 0
  277. except ValueError:
  278. use_hugepages = 0
  279. elif use_hugepage is None:
  280. # This is not Linux, so it should not matter, just enable anyway
  281. use_hugepage = 1
  282. else:
  283. use_hugepage = int(use_hugepage)
  284. # Note that this will currently only make a difference on Linux
  285. core.multiarray._set_madvise_hugepage(use_hugepage)