Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/__init__.py: 70%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2NumPy
3=====
5Provides
6 1. An array object of arbitrary homogeneous items
7 2. Fast mathematical operations over arrays
8 3. Linear Algebra, Fourier Transforms, Random Number Generation
10How to use the documentation
11----------------------------
12Documentation is available in two forms: docstrings provided
13with the code, and a loose standing reference guide, available from
14`the NumPy homepage <https://numpy.org>`_.
16We recommend exploring the docstrings using
17`IPython <https://ipython.org>`_, an advanced Python shell with
18TAB-completion and introspection capabilities. See below for further
19instructions.
21The docstring examples assume that `numpy` has been imported as ``np``::
23 >>> import numpy as np
25Code snippets are indicated by three greater-than signs::
27 >>> x = 42
28 >>> x = x + 1
30Use the built-in ``help`` function to view a function's docstring::
32 >>> help(np.sort)
33 ... # doctest: +SKIP
35For some objects, ``np.info(obj)`` may provide additional help. This is
36particularly true if you see the line "Help on ufunc object:" at the top
37of the help() page. Ufuncs are implemented in C, not Python, for speed.
38The native Python help() does not know how to view their help, but our
39np.info() function does.
41To search for documents containing a keyword, do::
43 >>> np.lookfor('keyword')
44 ... # doctest: +SKIP
46General-purpose documents like a glossary and help on the basic concepts
47of numpy are available under the ``doc`` sub-module::
49 >>> from numpy import doc
50 >>> help(doc)
51 ... # doctest: +SKIP
53Available subpackages
54---------------------
55lib
56 Basic functions used by several sub-packages.
57random
58 Core Random Tools
59linalg
60 Core Linear Algebra Tools
61fft
62 Core FFT routines
63polynomial
64 Polynomial tools
65testing
66 NumPy testing tools
67distutils
68 Enhancements to distutils with support for
69 Fortran compilers support and more (for Python <= 3.11).
71Utilities
72---------
73test
74 Run numpy unittests
75show_config
76 Show numpy build configuration
77matlib
78 Make everything matrices.
79__version__
80 NumPy version string
82Viewing documentation using IPython
83-----------------------------------
85Start IPython and import `numpy` usually under the alias ``np``: `import
86numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
87examples into the shell. To see which functions are available in `numpy`,
88type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
89``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
90down the list. To view the docstring for a function, use
91``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
92the source code).
94Copies vs. in-place operation
95-----------------------------
96Most of the functions in `numpy` return a copy of the array argument
97(e.g., `np.sort`). In-place versions of these functions are often
98available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
99Exceptions to this rule are documented.
101"""
102import sys
103import warnings
105from ._globals import _NoValue, _CopyMode
106# These exceptions were moved in 1.25 and are hidden from __dir__()
107from .exceptions import (
108 ComplexWarning, ModuleDeprecationWarning, VisibleDeprecationWarning,
109 TooHardError, AxisError)
112# If a version with git hash was stored, use that instead
113from . import version
114from .version import __version__
116# We first need to detect if we're being called as part of the numpy setup
117# procedure itself in a reliable manner.
118try:
119 __NUMPY_SETUP__
120except NameError:
121 __NUMPY_SETUP__ = False
123if __NUMPY_SETUP__:
124 sys.stderr.write('Running from numpy source directory.\n')
125else:
126 # Allow distributors to run custom init code before importing numpy.core
127 from . import _distributor_init
129 try:
130 from numpy.__config__ import show as show_config
131 except ImportError as e:
132 msg = """Error importing numpy: you should not try to import numpy from
133 its source directory; please exit the numpy source tree, and relaunch
134 your python interpreter from there."""
135 raise ImportError(msg) from e
137 __all__ = [
138 'exceptions', 'ModuleDeprecationWarning', 'VisibleDeprecationWarning',
139 'ComplexWarning', 'TooHardError', 'AxisError']
141 # mapping of {name: (value, deprecation_msg)}
142 __deprecated_attrs__ = {}
144 from . import core
145 from .core import *
146 from . import compat
147 from . import exceptions
148 from . import dtypes
149 from . import lib
150 # NOTE: to be revisited following future namespace cleanup.
151 # See gh-14454 and gh-15672 for discussion.
152 from .lib import *
154 from . import linalg
155 from . import fft
156 from . import polynomial
157 from . import random
158 from . import ctypeslib
159 from . import ma
160 from . import matrixlib as _mat
161 from .matrixlib import *
163 # Deprecations introduced in NumPy 1.20.0, 2020-06-06
164 import builtins as _builtins
166 _msg = (
167 "module 'numpy' has no attribute '{n}'.\n"
168 "`np.{n}` was a deprecated alias for the builtin `{n}`. "
169 "To avoid this error in existing code, use `{n}` by itself. "
170 "Doing this will not modify any behavior and is safe. {extended_msg}\n"
171 "The aliases was originally deprecated in NumPy 1.20; for more "
172 "details and guidance see the original release note at:\n"
173 " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
175 _specific_msg = (
176 "If you specifically wanted the numpy scalar type, use `np.{}` here.")
178 _int_extended_msg = (
179 "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
180 "or `np.int32` to specify the precision. If you wish to review "
181 "your current use, check the release note link for "
182 "additional information.")
184 _type_info = [
185 ("object", ""), # The NumPy scalar only exists by name.
186 ("bool", _specific_msg.format("bool_")),
187 ("float", _specific_msg.format("float64")),
188 ("complex", _specific_msg.format("complex128")),
189 ("str", _specific_msg.format("str_")),
190 ("int", _int_extended_msg.format("int"))]
192 __former_attrs__ = {
193 n: _msg.format(n=n, extended_msg=extended_msg)
194 for n, extended_msg in _type_info
195 }
197 # Future warning introduced in NumPy 1.24.0, 2022-11-17
198 _msg = (
199 "`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)")
201 # Some of these are awkward (since `np.str` may be preferable in the long
202 # term), but overall the names ending in 0 seem undesirable
203 _type_info = [
204 ("bool8", bool_, "np.bool_"),
205 ("int0", intp, "np.intp"),
206 ("uint0", uintp, "np.uintp"),
207 ("str0", str_, "np.str_"),
208 ("bytes0", bytes_, "np.bytes_"),
209 ("void0", void, "np.void"),
210 ("object0", object_,
211 "`np.object0` is a deprecated alias for `np.object_`. "
212 "`object` can be used instead. (Deprecated NumPy 1.24)")]
214 # Some of these could be defined right away, but most were aliases to
215 # the Python objects and only removed in NumPy 1.24. Defining them should
216 # probably wait for NumPy 1.26 or 2.0.
217 # When defined, these should possibly not be added to `__all__` to avoid
218 # import with `from numpy import *`.
219 __future_scalars__ = {"bool", "long", "ulong", "str", "bytes", "object"}
221 __deprecated_attrs__.update({
222 n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info})
224 import math
226 __deprecated_attrs__['math'] = (math,
227 "`np.math` is a deprecated alias for the standard library `math` "
228 "module (Deprecated Numpy 1.25). Replace usages of `np.math` with "
229 "`math`")
231 del math, _msg, _type_info
233 from .core import abs
234 # now that numpy modules are imported, can initialize limits
235 core.getlimits._register_known_types()
237 __all__.extend(['__version__', 'show_config'])
238 __all__.extend(core.__all__)
239 __all__.extend(_mat.__all__)
240 __all__.extend(lib.__all__)
241 __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
243 # Remove min and max from __all__ to avoid `from numpy import *` override
244 # the builtins min/max. Temporary fix for 1.25.x/1.26.x, see gh-24229.
245 __all__.remove('min')
246 __all__.remove('max')
247 __all__.remove('round')
249 # Remove one of the two occurrences of `issubdtype`, which is exposed as
250 # both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.
251 __all__.remove('issubdtype')
253 # These are exported by np.core, but are replaced by the builtins below
254 # remove them to ensure that we don't end up with `np.long == np.int_`,
255 # which would be a breaking change.
256 del long, unicode
257 __all__.remove('long')
258 __all__.remove('unicode')
260 # Remove things that are in the numpy.lib but not in the numpy namespace
261 # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
262 # that prevents adding more things to the main namespace by accident.
263 # The list below will grow until the `from .lib import *` fixme above is
264 # taken care of
265 __all__.remove('Arrayterator')
266 del Arrayterator
268 # These names were removed in NumPy 1.20. For at least one release,
269 # attempts to access these names in the numpy namespace will trigger
270 # a warning, and calling the function will raise an exception.
271 _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
272 'ppmt', 'pv', 'rate']
273 __expired_functions__ = {
274 name: (f'In accordance with NEP 32, the function {name} was removed '
275 'from NumPy version 1.20. A replacement for this function '
276 'is available in the numpy_financial library: '
277 'https://pypi.org/project/numpy-financial')
278 for name in _financial_names}
280 # Filter out Cython harmless warnings
281 warnings.filterwarnings("ignore", message="numpy.dtype size changed")
282 warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
283 warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
285 # oldnumeric and numarray were removed in 1.9. In case some packages import
286 # but do not use them, we define them here for backward compatibility.
287 oldnumeric = 'removed'
288 numarray = 'removed'
290 def __getattr__(attr):
291 # Warn for expired attributes, and return a dummy function
292 # that always raises an exception.
293 import warnings
294 import math
295 try:
296 msg = __expired_functions__[attr]
297 except KeyError:
298 pass
299 else:
300 warnings.warn(msg, DeprecationWarning, stacklevel=2)
302 def _expired(*args, **kwds):
303 raise RuntimeError(msg)
305 return _expired
307 # Emit warnings for deprecated attributes
308 try:
309 val, msg = __deprecated_attrs__[attr]
310 except KeyError:
311 pass
312 else:
313 warnings.warn(msg, DeprecationWarning, stacklevel=2)
314 return val
316 if attr in __future_scalars__:
317 # And future warnings for those that will change, but also give
318 # the AttributeError
319 warnings.warn(
320 f"In the future `np.{attr}` will be defined as the "
321 "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
323 if attr in __former_attrs__:
324 raise AttributeError(__former_attrs__[attr])
326 if attr == 'testing':
327 import numpy.testing as testing
328 return testing
329 elif attr == 'Tester':
330 "Removed in NumPy 1.25.0"
331 raise RuntimeError("Tester was removed in NumPy 1.25.")
333 raise AttributeError("module {!r} has no attribute "
334 "{!r}".format(__name__, attr))
336 def __dir__():
337 public_symbols = globals().keys() | {'testing'}
338 public_symbols -= {
339 "core", "matrixlib",
340 # These were moved in 1.25 and may be deprecated eventually:
341 "ModuleDeprecationWarning", "VisibleDeprecationWarning",
342 "ComplexWarning", "TooHardError", "AxisError"
343 }
344 return list(public_symbols)
346 # Pytest testing
347 from numpy._pytesttester import PytestTester
348 test = PytestTester(__name__)
349 del PytestTester
351 def _sanity_check():
352 """
353 Quick sanity checks for common bugs caused by environment.
354 There are some cases e.g. with wrong BLAS ABI that cause wrong
355 results under specific runtime conditions that are not necessarily
356 achieved during test suite runs, and it is useful to catch those early.
358 See https://github.com/numpy/numpy/issues/8577 and other
359 similar bug reports.
361 """
362 try:
363 x = ones(2, dtype=float32)
364 if not abs(x.dot(x) - float32(2.0)) < 1e-5:
365 raise AssertionError()
366 except AssertionError:
367 msg = ("The current Numpy installation ({!r}) fails to "
368 "pass simple sanity checks. This can be caused for example "
369 "by incorrect BLAS library being linked in, or by mixing "
370 "package managers (pip, conda, apt, ...). Search closed "
371 "numpy issues for similar problems.")
372 raise RuntimeError(msg.format(__file__)) from None
374 _sanity_check()
375 del _sanity_check
377 def _mac_os_check():
378 """
379 Quick Sanity check for Mac OS look for accelerate build bugs.
380 Testing numpy polyfit calls init_dgelsd(LAPACK)
381 """
382 try:
383 c = array([3., 2., 1.])
384 x = linspace(0, 2, 5)
385 y = polyval(c, x)
386 _ = polyfit(x, y, 2, cov=True)
387 except ValueError:
388 pass
390 if sys.platform == "darwin":
391 from . import exceptions
392 with warnings.catch_warnings(record=True) as w:
393 _mac_os_check()
394 # Throw runtime error, if the test failed Check for warning and error_message
395 if len(w) > 0:
396 for _wn in w:
397 if _wn.category is exceptions.RankWarning:
398 # Ignore other warnings, they may not be relevant (see gh-25433).
399 error_message = f"{_wn.category.__name__}: {str(_wn.message)}"
400 msg = (
401 "Polyfit sanity test emitted a warning, most likely due "
402 "to using a buggy Accelerate backend."
403 "\nIf you compiled yourself, more information is available at:"
404 "\nhttps://numpy.org/devdocs/building/index.html"
405 "\nOtherwise report this to the vendor "
406 "that provided NumPy.\n\n{}\n".format(error_message))
407 raise RuntimeError(msg)
408 del _wn
409 del w
410 del _mac_os_check
412 # We usually use madvise hugepages support, but on some old kernels it
413 # is slow and thus better avoided.
414 # Specifically kernel version 4.6 had a bug fix which probably fixed this:
415 # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
416 import os
417 use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
418 if sys.platform == "linux" and use_hugepage is None:
419 # If there is an issue with parsing the kernel version,
420 # set use_hugepages to 0. Usage of LooseVersion will handle
421 # the kernel version parsing better, but avoided since it
422 # will increase the import time. See: #16679 for related discussion.
423 try:
424 use_hugepage = 1
425 kernel_version = os.uname().release.split(".")[:2]
426 kernel_version = tuple(int(v) for v in kernel_version)
427 if kernel_version < (4, 6):
428 use_hugepage = 0
429 except ValueError:
430 use_hugepages = 0
431 elif use_hugepage is None:
432 # This is not Linux, so it should not matter, just enable anyway
433 use_hugepage = 1
434 else:
435 use_hugepage = int(use_hugepage)
437 # Note that this will currently only make a difference on Linux
438 core.multiarray._set_madvise_hugepage(use_hugepage)
439 del use_hugepage
441 # Give a warning if NumPy is reloaded or imported on a sub-interpreter
442 # We do this from python, since the C-module may not be reloaded and
443 # it is tidier organized.
444 core.multiarray._multiarray_umath._reload_guard()
446 # default to "weak" promotion for "NumPy 2".
447 core._set_promotion_state(
448 os.environ.get("NPY_PROMOTION_STATE",
449 "weak" if _using_numpy2_behavior() else "legacy"))
451 # Tell PyInstaller where to find hook-numpy.py
452 def _pyinstaller_hooks_dir():
453 from pathlib import Path
454 return [str(Path(__file__).with_name("_pyinstaller").resolve())]
456 # Remove symbols imported for internal use
457 del os
460# Remove symbols imported for internal use
461del sys, warnings