__init__.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. from __future__ import division, absolute_import, print_function
  89. import sys
  90. import warnings
  91. from ._globals import ModuleDeprecationWarning, VisibleDeprecationWarning
  92. from ._globals import _NoValue
  93. # We first need to detect if we're being called as part of the numpy setup
  94. # procedure itself in a reliable manner.
  95. try:
  96. __NUMPY_SETUP__
  97. except NameError:
  98. __NUMPY_SETUP__ = False
  99. if __NUMPY_SETUP__:
  100. sys.stderr.write('Running from numpy source directory.\n')
  101. else:
  102. try:
  103. from numpy.__config__ import show as show_config
  104. except ImportError:
  105. msg = """Error importing numpy: you should not try to import numpy from
  106. its source directory; please exit the numpy source tree, and relaunch
  107. your python interpreter from there."""
  108. raise ImportError(msg)
  109. from .version import git_revision as __git_revision__
  110. from .version import version as __version__
  111. __all__ = ['ModuleDeprecationWarning',
  112. 'VisibleDeprecationWarning']
  113. # Allow distributors to run custom init code
  114. from . import _distributor_init
  115. from . import core
  116. from .core import *
  117. from . import compat
  118. from . import lib
  119. # FIXME: why have numpy.lib if everything is imported here??
  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. from .compat import long
  130. # Make these accessible from numpy name-space
  131. # but not imported in from numpy import *
  132. # TODO[gh-6103]: Deprecate these
  133. if sys.version_info[0] >= 3:
  134. from builtins import bool, int, float, complex, object, str
  135. unicode = str
  136. else:
  137. from __builtin__ import bool, int, float, complex, object, unicode, str
  138. from .core import round, abs, max, min
  139. # now that numpy modules are imported, can initialize limits
  140. core.getlimits._register_known_types()
  141. __all__.extend(['__version__', 'show_config'])
  142. __all__.extend(core.__all__)
  143. __all__.extend(_mat.__all__)
  144. __all__.extend(lib.__all__)
  145. __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
  146. # These are added by `from .core import *` and `core.__all__`, but we
  147. # overwrite them above with builtins we do _not_ want to export.
  148. __all__.remove('long')
  149. __all__.remove('unicode')
  150. # Remove things that are in the numpy.lib but not in the numpy namespace
  151. # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
  152. # that prevents adding more things to the main namespace by accident.
  153. # The list below will grow until the `from .lib import *` fixme above is
  154. # taken care of
  155. __all__.remove('Arrayterator')
  156. del Arrayterator
  157. # Filter out Cython harmless warnings
  158. warnings.filterwarnings("ignore", message="numpy.dtype size changed")
  159. warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
  160. warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
  161. # oldnumeric and numarray were removed in 1.9. In case some packages import
  162. # but do not use them, we define them here for backward compatibility.
  163. oldnumeric = 'removed'
  164. numarray = 'removed'
  165. if sys.version_info[:2] >= (3, 7):
  166. # Importing Tester requires importing all of UnitTest which is not a
  167. # cheap import Since it is mainly used in test suits, we lazy import it
  168. # here to save on the order of 10 ms of import time for most users
  169. #
  170. # The previous way Tester was imported also had a side effect of adding
  171. # the full `numpy.testing` namespace
  172. #
  173. # module level getattr is only supported in 3.7 onwards
  174. # https://www.python.org/dev/peps/pep-0562/
  175. def __getattr__(attr):
  176. if attr == 'testing':
  177. import numpy.testing as testing
  178. return testing
  179. elif attr == 'Tester':
  180. from .testing import Tester
  181. return Tester
  182. else:
  183. raise AttributeError("module {!r} has no attribute "
  184. "{!r}".format(__name__, attr))
  185. def __dir__():
  186. return list(globals().keys()) + ['Tester', 'testing']
  187. else:
  188. # We don't actually use this ourselves anymore, but I'm not 100% sure that
  189. # no-one else in the world is using it (though I hope not)
  190. from .testing import Tester
  191. # Pytest testing
  192. from numpy._pytesttester import PytestTester
  193. test = PytestTester(__name__)
  194. del PytestTester
  195. def _sanity_check():
  196. """
  197. Quick sanity checks for common bugs caused by environment.
  198. There are some cases e.g. with wrong BLAS ABI that cause wrong
  199. results under specific runtime conditions that are not necessarily
  200. achieved during test suite runs, and it is useful to catch those early.
  201. See https://github.com/numpy/numpy/issues/8577 and other
  202. similar bug reports.
  203. """
  204. try:
  205. x = ones(2, dtype=float32)
  206. if not abs(x.dot(x) - 2.0) < 1e-5:
  207. raise AssertionError()
  208. except AssertionError:
  209. msg = ("The current Numpy installation ({!r}) fails to "
  210. "pass simple sanity checks. This can be caused for example "
  211. "by incorrect BLAS library being linked in, or by mixing "
  212. "package managers (pip, conda, apt, ...). Search closed "
  213. "numpy issues for similar problems.")
  214. raise RuntimeError(msg.format(__file__))
  215. _sanity_check()
  216. del _sanity_check