__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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://numpy.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. lib
  41. Basic functions used by several sub-packages.
  42. random
  43. Core Random Tools
  44. linalg
  45. Core Linear Algebra Tools
  46. fft
  47. Core FFT routines
  48. polynomial
  49. Polynomial tools
  50. testing
  51. NumPy testing tools
  52. distutils
  53. Enhancements to distutils with support for
  54. Fortran compilers support and more (for Python <= 3.11).
  55. Utilities
  56. ---------
  57. test
  58. Run numpy unittests
  59. show_config
  60. Show numpy build configuration
  61. matlib
  62. Make everything matrices.
  63. __version__
  64. NumPy version string
  65. Viewing documentation using IPython
  66. -----------------------------------
  67. Start IPython and import `numpy` usually under the alias ``np``: `import
  68. numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
  69. examples into the shell. To see which functions are available in `numpy`,
  70. type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
  71. ``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
  72. down the list. To view the docstring for a function, use
  73. ``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
  74. the source code).
  75. Copies vs. in-place operation
  76. -----------------------------
  77. Most of the functions in `numpy` return a copy of the array argument
  78. (e.g., `np.sort`). In-place versions of these functions are often
  79. available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
  80. Exceptions to this rule are documented.
  81. """
  82. import sys
  83. import warnings
  84. from ._globals import _NoValue, _CopyMode
  85. # These exceptions were moved in 1.25 and are hidden from __dir__()
  86. from .exceptions import (
  87. ComplexWarning, ModuleDeprecationWarning, VisibleDeprecationWarning,
  88. TooHardError, AxisError)
  89. # If a version with git hash was stored, use that instead
  90. from . import version
  91. from .version import __version__
  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. # Allow distributors to run custom init code before importing numpy.core
  102. from . import _distributor_init
  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. __all__ = [
  111. 'exceptions', 'ModuleDeprecationWarning', 'VisibleDeprecationWarning',
  112. 'ComplexWarning', 'TooHardError', 'AxisError']
  113. # mapping of {name: (value, deprecation_msg)}
  114. __deprecated_attrs__ = {}
  115. from . import core
  116. from .core import *
  117. from . import compat
  118. from . import exceptions
  119. from . import dtypes
  120. from . import lib
  121. # NOTE: to be revisited following future namespace cleanup.
  122. # See gh-14454 and gh-15672 for discussion.
  123. from .lib import *
  124. from . import linalg
  125. from . import fft
  126. from . import polynomial
  127. from . import random
  128. from . import ctypeslib
  129. from . import ma
  130. from . import matrixlib as _mat
  131. from .matrixlib import *
  132. # Deprecations introduced in NumPy 1.20.0, 2020-06-06
  133. import builtins as _builtins
  134. _msg = (
  135. "module 'numpy' has no attribute '{n}'.\n"
  136. "`np.{n}` was a deprecated alias for the builtin `{n}`. "
  137. "To avoid this error in existing code, use `{n}` by itself. "
  138. "Doing this will not modify any behavior and is safe. {extended_msg}\n"
  139. "The aliases was originally deprecated in NumPy 1.20; for more "
  140. "details and guidance see the original release note at:\n"
  141. " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
  142. _specific_msg = (
  143. "If you specifically wanted the numpy scalar type, use `np.{}` here.")
  144. _int_extended_msg = (
  145. "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
  146. "or `np.int32` to specify the precision. If you wish to review "
  147. "your current use, check the release note link for "
  148. "additional information.")
  149. _type_info = [
  150. ("object", ""), # The NumPy scalar only exists by name.
  151. ("bool", _specific_msg.format("bool_")),
  152. ("float", _specific_msg.format("float64")),
  153. ("complex", _specific_msg.format("complex128")),
  154. ("str", _specific_msg.format("str_")),
  155. ("int", _int_extended_msg.format("int"))]
  156. __former_attrs__ = {
  157. n: _msg.format(n=n, extended_msg=extended_msg)
  158. for n, extended_msg in _type_info
  159. }
  160. # Future warning introduced in NumPy 1.24.0, 2022-11-17
  161. _msg = (
  162. "`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)")
  163. # Some of these are awkward (since `np.str` may be preferable in the long
  164. # term), but overall the names ending in 0 seem undesirable
  165. _type_info = [
  166. ("bool8", bool_, "np.bool_"),
  167. ("int0", intp, "np.intp"),
  168. ("uint0", uintp, "np.uintp"),
  169. ("str0", str_, "np.str_"),
  170. ("bytes0", bytes_, "np.bytes_"),
  171. ("void0", void, "np.void"),
  172. ("object0", object_,
  173. "`np.object0` is a deprecated alias for `np.object_`. "
  174. "`object` can be used instead. (Deprecated NumPy 1.24)")]
  175. # Some of these could be defined right away, but most were aliases to
  176. # the Python objects and only removed in NumPy 1.24. Defining them should
  177. # probably wait for NumPy 1.26 or 2.0.
  178. # When defined, these should possibly not be added to `__all__` to avoid
  179. # import with `from numpy import *`.
  180. __future_scalars__ = {"bool", "long", "ulong", "str", "bytes", "object"}
  181. __deprecated_attrs__.update({
  182. n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info})
  183. import math
  184. __deprecated_attrs__['math'] = (math,
  185. "`np.math` is a deprecated alias for the standard library `math` "
  186. "module (Deprecated Numpy 1.25). Replace usages of `np.math` with "
  187. "`math`")
  188. del math, _msg, _type_info
  189. from .core import abs
  190. # now that numpy modules are imported, can initialize limits
  191. core.getlimits._register_known_types()
  192. __all__.extend(['__version__', 'show_config'])
  193. __all__.extend(core.__all__)
  194. __all__.extend(_mat.__all__)
  195. __all__.extend(lib.__all__)
  196. __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
  197. # Remove min and max from __all__ to avoid `from numpy import *` override
  198. # the builtins min/max. Temporary fix for 1.25.x/1.26.x, see gh-24229.
  199. __all__.remove('min')
  200. __all__.remove('max')
  201. __all__.remove('round')
  202. # Remove one of the two occurrences of `issubdtype`, which is exposed as
  203. # both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.
  204. __all__.remove('issubdtype')
  205. # These are exported by np.core, but are replaced by the builtins below
  206. # remove them to ensure that we don't end up with `np.long == np.int_`,
  207. # which would be a breaking change.
  208. del long, unicode
  209. __all__.remove('long')
  210. __all__.remove('unicode')
  211. # Remove things that are in the numpy.lib but not in the numpy namespace
  212. # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
  213. # that prevents adding more things to the main namespace by accident.
  214. # The list below will grow until the `from .lib import *` fixme above is
  215. # taken care of
  216. __all__.remove('Arrayterator')
  217. del Arrayterator
  218. # These names were removed in NumPy 1.20. For at least one release,
  219. # attempts to access these names in the numpy namespace will trigger
  220. # a warning, and calling the function will raise an exception.
  221. _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
  222. 'ppmt', 'pv', 'rate']
  223. __expired_functions__ = {
  224. name: (f'In accordance with NEP 32, the function {name} was removed '
  225. 'from NumPy version 1.20. A replacement for this function '
  226. 'is available in the numpy_financial library: '
  227. 'https://pypi.org/project/numpy-financial')
  228. for name in _financial_names}
  229. # Filter out Cython harmless warnings
  230. warnings.filterwarnings("ignore", message="numpy.dtype size changed")
  231. warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
  232. warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
  233. # oldnumeric and numarray were removed in 1.9. In case some packages import
  234. # but do not use them, we define them here for backward compatibility.
  235. oldnumeric = 'removed'
  236. numarray = 'removed'
  237. def __getattr__(attr):
  238. # Warn for expired attributes, and return a dummy function
  239. # that always raises an exception.
  240. import warnings
  241. import math
  242. try:
  243. msg = __expired_functions__[attr]
  244. except KeyError:
  245. pass
  246. else:
  247. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  248. def _expired(*args, **kwds):
  249. raise RuntimeError(msg)
  250. return _expired
  251. # Emit warnings for deprecated attributes
  252. try:
  253. val, msg = __deprecated_attrs__[attr]
  254. except KeyError:
  255. pass
  256. else:
  257. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  258. return val
  259. if attr in __future_scalars__:
  260. # And future warnings for those that will change, but also give
  261. # the AttributeError
  262. warnings.warn(
  263. f"In the future `np.{attr}` will be defined as the "
  264. "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
  265. if attr in __former_attrs__:
  266. raise AttributeError(__former_attrs__[attr])
  267. if attr == 'testing':
  268. import numpy.testing as testing
  269. return testing
  270. elif attr == 'Tester':
  271. "Removed in NumPy 1.25.0"
  272. raise RuntimeError("Tester was removed in NumPy 1.25.")
  273. raise AttributeError("module {!r} has no attribute "
  274. "{!r}".format(__name__, attr))
  275. def __dir__():
  276. public_symbols = globals().keys() | {'testing'}
  277. public_symbols -= {
  278. "core", "matrixlib",
  279. # These were moved in 1.25 and may be deprecated eventually:
  280. "ModuleDeprecationWarning", "VisibleDeprecationWarning",
  281. "ComplexWarning", "TooHardError", "AxisError"
  282. }
  283. return list(public_symbols)
  284. # Pytest testing
  285. from numpy._pytesttester import PytestTester
  286. test = PytestTester(__name__)
  287. del PytestTester
  288. def _sanity_check():
  289. """
  290. Quick sanity checks for common bugs caused by environment.
  291. There are some cases e.g. with wrong BLAS ABI that cause wrong
  292. results under specific runtime conditions that are not necessarily
  293. achieved during test suite runs, and it is useful to catch those early.
  294. See https://github.com/numpy/numpy/issues/8577 and other
  295. similar bug reports.
  296. """
  297. try:
  298. x = ones(2, dtype=float32)
  299. if not abs(x.dot(x) - float32(2.0)) < 1e-5:
  300. raise AssertionError()
  301. except AssertionError:
  302. msg = ("The current Numpy installation ({!r}) fails to "
  303. "pass simple sanity checks. This can be caused for example "
  304. "by incorrect BLAS library being linked in, or by mixing "
  305. "package managers (pip, conda, apt, ...). Search closed "
  306. "numpy issues for similar problems.")
  307. raise RuntimeError(msg.format(__file__)) from None
  308. _sanity_check()
  309. del _sanity_check
  310. def _mac_os_check():
  311. """
  312. Quick Sanity check for Mac OS look for accelerate build bugs.
  313. Testing numpy polyfit calls init_dgelsd(LAPACK)
  314. """
  315. try:
  316. c = array([3., 2., 1.])
  317. x = linspace(0, 2, 5)
  318. y = polyval(c, x)
  319. _ = polyfit(x, y, 2, cov=True)
  320. except ValueError:
  321. pass
  322. if sys.platform == "darwin":
  323. from . import exceptions
  324. with warnings.catch_warnings(record=True) as w:
  325. _mac_os_check()
  326. # Throw runtime error, if the test failed Check for warning and error_message
  327. if len(w) > 0:
  328. for _wn in w:
  329. if _wn.category is exceptions.RankWarning:
  330. # Ignore other warnings, they may not be relevant (see gh-25433).
  331. error_message = f"{_wn.category.__name__}: {str(_wn.message)}"
  332. msg = (
  333. "Polyfit sanity test emitted a warning, most likely due "
  334. "to using a buggy Accelerate backend."
  335. "\nIf you compiled yourself, more information is available at:"
  336. "\nhttps://numpy.org/devdocs/building/index.html"
  337. "\nOtherwise report this to the vendor "
  338. "that provided NumPy.\n\n{}\n".format(error_message))
  339. raise RuntimeError(msg)
  340. del _wn
  341. del w
  342. del _mac_os_check
  343. # We usually use madvise hugepages support, but on some old kernels it
  344. # is slow and thus better avoided.
  345. # Specifically kernel version 4.6 had a bug fix which probably fixed this:
  346. # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
  347. import os
  348. use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
  349. if sys.platform == "linux" and use_hugepage is None:
  350. # If there is an issue with parsing the kernel version,
  351. # set use_hugepages to 0. Usage of LooseVersion will handle
  352. # the kernel version parsing better, but avoided since it
  353. # will increase the import time. See: #16679 for related discussion.
  354. try:
  355. use_hugepage = 1
  356. kernel_version = os.uname().release.split(".")[:2]
  357. kernel_version = tuple(int(v) for v in kernel_version)
  358. if kernel_version < (4, 6):
  359. use_hugepage = 0
  360. except ValueError:
  361. use_hugepages = 0
  362. elif use_hugepage is None:
  363. # This is not Linux, so it should not matter, just enable anyway
  364. use_hugepage = 1
  365. else:
  366. use_hugepage = int(use_hugepage)
  367. # Note that this will currently only make a difference on Linux
  368. core.multiarray._set_madvise_hugepage(use_hugepage)
  369. del use_hugepage
  370. # Give a warning if NumPy is reloaded or imported on a sub-interpreter
  371. # We do this from python, since the C-module may not be reloaded and
  372. # it is tidier organized.
  373. core.multiarray._multiarray_umath._reload_guard()
  374. # default to "weak" promotion for "NumPy 2".
  375. core._set_promotion_state(
  376. os.environ.get("NPY_PROMOTION_STATE",
  377. "weak" if _using_numpy2_behavior() else "legacy"))
  378. # Tell PyInstaller where to find hook-numpy.py
  379. def _pyinstaller_hooks_dir():
  380. from pathlib import Path
  381. return [str(Path(__file__).with_name("_pyinstaller").resolve())]
  382. # Remove symbols imported for internal use
  383. del os
  384. # Remove symbols imported for internal use
  385. del sys, warnings