__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. Note: `numpy.dual` is deprecated. Use the functions from NumPy or Scipy
  68. directly instead of importing them from `numpy.dual`.
  69. matlib
  70. Make everything matrices.
  71. __version__
  72. NumPy version string
  73. Viewing documentation using IPython
  74. -----------------------------------
  75. Start IPython with the NumPy profile (``ipython -p numpy``), which will
  76. import `numpy` under the alias `np`. Then, use the ``cpaste`` command to
  77. paste examples into the shell. To see which functions are available in
  78. `numpy`, type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
  79. ``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
  80. down the list. To view the docstring for a function, use
  81. ``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
  82. the source code).
  83. Copies vs. in-place operation
  84. -----------------------------
  85. Most of the functions in `numpy` return a copy of the array argument
  86. (e.g., `np.sort`). In-place versions of these functions are often
  87. available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
  88. Exceptions to this rule are documented.
  89. """
  90. import sys
  91. import warnings
  92. from ._globals import ModuleDeprecationWarning, VisibleDeprecationWarning
  93. from ._globals import _NoValue
  94. # We first need to detect if we're being called as part of the numpy setup
  95. # procedure itself in a reliable manner.
  96. try:
  97. __NUMPY_SETUP__
  98. except NameError:
  99. __NUMPY_SETUP__ = False
  100. if __NUMPY_SETUP__:
  101. sys.stderr.write('Running from numpy source directory.\n')
  102. else:
  103. try:
  104. from numpy.__config__ import show as show_config
  105. except ImportError as e:
  106. msg = """Error importing numpy: you should not try to import numpy from
  107. its source directory; please exit the numpy source tree, and relaunch
  108. your python interpreter from there."""
  109. raise ImportError(msg) from e
  110. from .version import git_revision as __git_revision__
  111. from .version import version as __version__
  112. __all__ = ['ModuleDeprecationWarning',
  113. 'VisibleDeprecationWarning']
  114. # mapping of {name: (value, deprecation_msg)}
  115. __deprecated_attrs__ = {}
  116. # Allow distributors to run custom init code
  117. from . import _distributor_init
  118. from . import core
  119. from .core import *
  120. from . import compat
  121. from . import lib
  122. # NOTE: to be revisited following future namespace cleanup.
  123. # See gh-14454 and gh-15672 for discussion.
  124. from .lib import *
  125. from . import linalg
  126. from . import fft
  127. from . import polynomial
  128. from . import random
  129. from . import ctypeslib
  130. from . import ma
  131. from . import matrixlib as _mat
  132. from .matrixlib import *
  133. # Deprecations introduced in NumPy 1.20.0, 2020-06-06
  134. import builtins as _builtins
  135. _msg = (
  136. "`np.{n}` is a deprecated alias for the builtin `{n}`. "
  137. "To silence this warning, use `{n}` by itself. Doing this will not "
  138. "modify any behavior and is safe. {extended_msg}\n"
  139. "Deprecated in NumPy 1.20; for more details and guidance: "
  140. "https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
  141. _specific_msg = (
  142. "If you specifically wanted the numpy scalar type, use `np.{}` here.")
  143. _int_extended_msg = (
  144. "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
  145. "or `np.int32` to specify the precision. If you wish to review "
  146. "your current use, check the release note link for "
  147. "additional information.")
  148. _type_info = [
  149. ("object", ""), # The NumPy scalar only exists by name.
  150. ("bool", _specific_msg.format("bool_")),
  151. ("float", _specific_msg.format("float64")),
  152. ("complex", _specific_msg.format("complex128")),
  153. ("str", _specific_msg.format("str_")),
  154. ("int", _int_extended_msg.format("int"))]
  155. __deprecated_attrs__.update({
  156. n: (getattr(_builtins, n), _msg.format(n=n, extended_msg=extended_msg))
  157. for n, extended_msg in _type_info
  158. })
  159. _msg = (
  160. "`np.{n}` is a deprecated alias for `np.compat.{n}`. "
  161. "To silence this warning, use `np.compat.{n}` by itself. "
  162. "In the likely event your code does not need to work on Python 2 "
  163. "you can use the builtin `{n2}` for which `np.compat.{n}` is itself "
  164. "an alias. Doing this will not modify any behaviour and is safe. "
  165. "{extended_msg}\n"
  166. "Deprecated in NumPy 1.20; for more details and guidance: "
  167. "https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
  168. __deprecated_attrs__["long"] = (
  169. getattr(compat, "long"),
  170. _msg.format(n="long", n2="int",
  171. extended_msg=_int_extended_msg.format("long")))
  172. __deprecated_attrs__["unicode"] = (
  173. getattr(compat, "unicode"),
  174. _msg.format(n="unicode", n2="str",
  175. extended_msg=_specific_msg.format("str_")))
  176. del _msg, _specific_msg, _int_extended_msg, _type_info, _builtins
  177. from .core import round, abs, max, min
  178. # now that numpy modules are imported, can initialize limits
  179. core.getlimits._register_known_types()
  180. __all__.extend(['__version__', 'show_config'])
  181. __all__.extend(core.__all__)
  182. __all__.extend(_mat.__all__)
  183. __all__.extend(lib.__all__)
  184. __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
  185. # These are exported by np.core, but are replaced by the builtins below
  186. # remove them to ensure that we don't end up with `np.long == np.int_`,
  187. # which would be a breaking change.
  188. del long, unicode
  189. __all__.remove('long')
  190. __all__.remove('unicode')
  191. # Remove things that are in the numpy.lib but not in the numpy namespace
  192. # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
  193. # that prevents adding more things to the main namespace by accident.
  194. # The list below will grow until the `from .lib import *` fixme above is
  195. # taken care of
  196. __all__.remove('Arrayterator')
  197. del Arrayterator
  198. # These names were removed in NumPy 1.20. For at least one release,
  199. # attempts to access these names in the numpy namespace will trigger
  200. # a warning, and calling the function will raise an exception.
  201. _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
  202. 'ppmt', 'pv', 'rate']
  203. __expired_functions__ = {
  204. name: (f'In accordance with NEP 32, the function {name} was removed '
  205. 'from NumPy version 1.20. A replacement for this function '
  206. 'is available in the numpy_financial library: '
  207. 'https://pypi.org/project/numpy-financial')
  208. for name in _financial_names}
  209. # Filter out Cython harmless warnings
  210. warnings.filterwarnings("ignore", message="numpy.dtype size changed")
  211. warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
  212. warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
  213. # oldnumeric and numarray were removed in 1.9. In case some packages import
  214. # but do not use them, we define them here for backward compatibility.
  215. oldnumeric = 'removed'
  216. numarray = 'removed'
  217. if sys.version_info[:2] >= (3, 7):
  218. # module level getattr is only supported in 3.7 onwards
  219. # https://www.python.org/dev/peps/pep-0562/
  220. def __getattr__(attr):
  221. # Warn for expired attributes, and return a dummy function
  222. # that always raises an exception.
  223. try:
  224. msg = __expired_functions__[attr]
  225. except KeyError:
  226. pass
  227. else:
  228. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  229. def _expired(*args, **kwds):
  230. raise RuntimeError(msg)
  231. return _expired
  232. # Emit warnings for deprecated attributes
  233. try:
  234. val, msg = __deprecated_attrs__[attr]
  235. except KeyError:
  236. pass
  237. else:
  238. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  239. return val
  240. # Importing Tester requires importing all of UnitTest which is not a
  241. # cheap import Since it is mainly used in test suits, we lazy import it
  242. # here to save on the order of 10 ms of import time for most users
  243. #
  244. # The previous way Tester was imported also had a side effect of adding
  245. # the full `numpy.testing` namespace
  246. if attr == 'testing':
  247. import numpy.testing as testing
  248. return testing
  249. elif attr == 'Tester':
  250. from .testing import Tester
  251. return Tester
  252. raise AttributeError("module {!r} has no attribute "
  253. "{!r}".format(__name__, attr))
  254. def __dir__():
  255. return list(globals().keys() | {'Tester', 'testing'})
  256. else:
  257. # We don't actually use this ourselves anymore, but I'm not 100% sure that
  258. # no-one else in the world is using it (though I hope not)
  259. from .testing import Tester
  260. # We weren't able to emit a warning about these, so keep them around
  261. globals().update({
  262. k: v
  263. for k, (v, msg) in __deprecated_attrs__.items()
  264. })
  265. # Pytest testing
  266. from numpy._pytesttester import PytestTester
  267. test = PytestTester(__name__)
  268. del PytestTester
  269. def _sanity_check():
  270. """
  271. Quick sanity checks for common bugs caused by environment.
  272. There are some cases e.g. with wrong BLAS ABI that cause wrong
  273. results under specific runtime conditions that are not necessarily
  274. achieved during test suite runs, and it is useful to catch those early.
  275. See https://github.com/numpy/numpy/issues/8577 and other
  276. similar bug reports.
  277. """
  278. try:
  279. x = ones(2, dtype=float32)
  280. if not abs(x.dot(x) - 2.0) < 1e-5:
  281. raise AssertionError()
  282. except AssertionError:
  283. msg = ("The current Numpy installation ({!r}) fails to "
  284. "pass simple sanity checks. This can be caused for example "
  285. "by incorrect BLAS library being linked in, or by mixing "
  286. "package managers (pip, conda, apt, ...). Search closed "
  287. "numpy issues for similar problems.")
  288. raise RuntimeError(msg.format(__file__)) from None
  289. _sanity_check()
  290. del _sanity_check
  291. def _mac_os_check():
  292. """
  293. Quick Sanity check for Mac OS look for accelerate build bugs.
  294. Testing numpy polyfit calls init_dgelsd(LAPACK)
  295. """
  296. try:
  297. c = array([3., 2., 1.])
  298. x = linspace(0, 2, 5)
  299. y = polyval(c, x)
  300. _ = polyfit(x, y, 2, cov=True)
  301. except ValueError:
  302. pass
  303. import sys
  304. if sys.platform == "darwin":
  305. with warnings.catch_warnings(record=True) as w:
  306. _mac_os_check()
  307. # Throw runtime error, if the test failed Check for warning and error_message
  308. error_message = ""
  309. if len(w) > 0:
  310. error_message = "{}: {}".format(w[-1].category.__name__, str(w[-1].message))
  311. msg = (
  312. "Polyfit sanity test emitted a warning, most likely due "
  313. "to using a buggy Accelerate backend. If you compiled "
  314. "yourself, more information is available at "
  315. "https://numpy.org/doc/stable/user/building.html#accelerated-blas-lapack-libraries "
  316. "Otherwise report this to the vendor "
  317. "that provided NumPy.\n{}\n".format(error_message))
  318. raise RuntimeError(msg)
  319. del _mac_os_check
  320. # We usually use madvise hugepages support, but on some old kernels it
  321. # is slow and thus better avoided.
  322. # Specifically kernel version 4.6 had a bug fix which probably fixed this:
  323. # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
  324. import os
  325. use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
  326. if sys.platform == "linux" and use_hugepage is None:
  327. # If there is an issue with parsing the kernel version,
  328. # set use_hugepages to 0. Usage of LooseVersion will handle
  329. # the kernel version parsing better, but avoided since it
  330. # will increase the import time. See: #16679 for related discussion.
  331. try:
  332. use_hugepage = 1
  333. kernel_version = os.uname().release.split(".")[:2]
  334. kernel_version = tuple(int(v) for v in kernel_version)
  335. if kernel_version < (4, 6):
  336. use_hugepage = 0
  337. except ValueError:
  338. use_hugepages = 0
  339. elif use_hugepage is None:
  340. # This is not Linux, so it should not matter, just enable anyway
  341. use_hugepage = 1
  342. else:
  343. use_hugepage = int(use_hugepage)
  344. # Note that this will currently only make a difference on Linux
  345. core.multiarray._set_madvise_hugepage(use_hugepage)