Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/numpy/__init__.py: 69%
147 statements
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:27 +0000
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:27 +0000
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.
71Utilities
72---------
73test
74 Run numpy unittests
75show_config
76 Show numpy build configuration
77dual
78 Overwrite certain functions with high-performance SciPy tools.
79 Note: `numpy.dual` is deprecated. Use the functions from NumPy or Scipy
80 directly instead of importing them from `numpy.dual`.
81matlib
82 Make everything matrices.
83__version__
84 NumPy version string
86Viewing documentation using IPython
87-----------------------------------
89Start IPython and import `numpy` usually under the alias ``np``: `import
90numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
91examples into the shell. To see which functions are available in `numpy`,
92type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
93``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
94down the list. To view the docstring for a function, use
95``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
96the source code).
98Copies vs. in-place operation
99-----------------------------
100Most of the functions in `numpy` return a copy of the array argument
101(e.g., `np.sort`). In-place versions of these functions are often
102available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
103Exceptions to this rule are documented.
105"""
106import sys
107import warnings
109from ._globals import _NoValue, _CopyMode
110# These exceptions were moved in 1.25 and are hidden from __dir__()
111from .exceptions import (
112 ComplexWarning, ModuleDeprecationWarning, VisibleDeprecationWarning,
113 TooHardError, AxisError)
115# We first need to detect if we're being called as part of the numpy setup
116# procedure itself in a reliable manner.
117try:
118 __NUMPY_SETUP__
119except NameError:
120 __NUMPY_SETUP__ = False
122if __NUMPY_SETUP__:
123 sys.stderr.write('Running from numpy source directory.\n')
124else:
125 try:
126 from numpy.__config__ import show as show_config
127 except ImportError as e:
128 msg = """Error importing numpy: you should not try to import numpy from
129 its source directory; please exit the numpy source tree, and relaunch
130 your python interpreter from there."""
131 raise ImportError(msg) from e
133 __all__ = [
134 'exceptions', 'ModuleDeprecationWarning', 'VisibleDeprecationWarning',
135 'ComplexWarning', 'TooHardError', 'AxisError']
137 # mapping of {name: (value, deprecation_msg)}
138 __deprecated_attrs__ = {}
140 # Allow distributors to run custom init code
141 from . import _distributor_init
143 from . import core
144 from .core import *
145 from . import compat
146 from . import exceptions
147 from . import lib
148 # NOTE: to be revisited following future namespace cleanup.
149 # See gh-14454 and gh-15672 for discussion.
150 from .lib import *
152 from . import linalg
153 from . import fft
154 from . import polynomial
155 from . import random
156 from . import ctypeslib
157 from . import ma
158 from . import matrixlib as _mat
159 from .matrixlib import *
161 # Deprecations introduced in NumPy 1.20.0, 2020-06-06
162 import builtins as _builtins
164 _msg = (
165 "module 'numpy' has no attribute '{n}'.\n"
166 "`np.{n}` was a deprecated alias for the builtin `{n}`. "
167 "To avoid this error in existing code, use `{n}` by itself. "
168 "Doing this will not modify any behavior and is safe. {extended_msg}\n"
169 "The aliases was originally deprecated in NumPy 1.20; for more "
170 "details and guidance see the original release note at:\n"
171 " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
173 _specific_msg = (
174 "If you specifically wanted the numpy scalar type, use `np.{}` here.")
176 _int_extended_msg = (
177 "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
178 "or `np.int32` to specify the precision. If you wish to review "
179 "your current use, check the release note link for "
180 "additional information.")
182 _type_info = [
183 ("object", ""), # The NumPy scalar only exists by name.
184 ("bool", _specific_msg.format("bool_")),
185 ("float", _specific_msg.format("float64")),
186 ("complex", _specific_msg.format("complex128")),
187 ("str", _specific_msg.format("str_")),
188 ("int", _int_extended_msg.format("int"))]
190 __former_attrs__ = {
191 n: _msg.format(n=n, extended_msg=extended_msg)
192 for n, extended_msg in _type_info
193 }
195 # Future warning introduced in NumPy 1.24.0, 2022-11-17
196 _msg = (
197 "`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)")
199 # Some of these are awkward (since `np.str` may be preferable in the long
200 # term), but overall the names ending in 0 seem undesireable
201 _type_info = [
202 ("bool8", bool_, "np.bool_"),
203 ("int0", intp, "np.intp"),
204 ("uint0", uintp, "np.uintp"),
205 ("str0", str_, "np.str_"),
206 ("bytes0", bytes_, "np.bytes_"),
207 ("void0", void, "np.void"),
208 ("object0", object_,
209 "`np.object0` is a deprecated alias for `np.object_`. "
210 "`object` can be used instead. (Deprecated NumPy 1.24)")]
212 # Some of these could be defined right away, but most were aliases to
213 # the Python objects and only removed in NumPy 1.24. Defining them should
214 # probably wait for NumPy 1.26 or 2.0.
215 # When defined, these should possibly not be added to `__all__` to avoid
216 # import with `from numpy import *`.
217 __future_scalars__ = {"bool", "long", "ulong", "str", "bytes", "object"}
219 __deprecated_attrs__.update({
220 n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info})
222 del _msg, _type_info
224 from .core import round, abs, max, min
225 # now that numpy modules are imported, can initialize limits
226 core.getlimits._register_known_types()
228 __all__.extend(['__version__', 'show_config'])
229 __all__.extend(core.__all__)
230 __all__.extend(_mat.__all__)
231 __all__.extend(lib.__all__)
232 __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
234 # Remove one of the two occurrences of `issubdtype`, which is exposed as
235 # both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.
236 __all__.remove('issubdtype')
238 # These are exported by np.core, but are replaced by the builtins below
239 # remove them to ensure that we don't end up with `np.long == np.int_`,
240 # which would be a breaking change.
241 del long, unicode
242 __all__.remove('long')
243 __all__.remove('unicode')
245 # Remove things that are in the numpy.lib but not in the numpy namespace
246 # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
247 # that prevents adding more things to the main namespace by accident.
248 # The list below will grow until the `from .lib import *` fixme above is
249 # taken care of
250 __all__.remove('Arrayterator')
251 del Arrayterator
253 # These names were removed in NumPy 1.20. For at least one release,
254 # attempts to access these names in the numpy namespace will trigger
255 # a warning, and calling the function will raise an exception.
256 _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
257 'ppmt', 'pv', 'rate']
258 __expired_functions__ = {
259 name: (f'In accordance with NEP 32, the function {name} was removed '
260 'from NumPy version 1.20. A replacement for this function '
261 'is available in the numpy_financial library: '
262 'https://pypi.org/project/numpy-financial')
263 for name in _financial_names}
265 # Filter out Cython harmless warnings
266 warnings.filterwarnings("ignore", message="numpy.dtype size changed")
267 warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
268 warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
270 # oldnumeric and numarray were removed in 1.9. In case some packages import
271 # but do not use them, we define them here for backward compatibility.
272 oldnumeric = 'removed'
273 numarray = 'removed'
275 def __getattr__(attr):
276 # Warn for expired attributes, and return a dummy function
277 # that always raises an exception.
278 import warnings
279 try:
280 msg = __expired_functions__[attr]
281 except KeyError:
282 pass
283 else:
284 warnings.warn(msg, DeprecationWarning, stacklevel=2)
286 def _expired(*args, **kwds):
287 raise RuntimeError(msg)
289 return _expired
291 # Emit warnings for deprecated attributes
292 try:
293 val, msg = __deprecated_attrs__[attr]
294 except KeyError:
295 pass
296 else:
297 warnings.warn(msg, DeprecationWarning, stacklevel=2)
298 return val
300 if attr in __future_scalars__:
301 # And future warnings for those that will change, but also give
302 # the AttributeError
303 warnings.warn(
304 f"In the future `np.{attr}` will be defined as the "
305 "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
307 if attr in __former_attrs__:
308 raise AttributeError(__former_attrs__[attr])
310 # Importing Tester requires importing all of UnitTest which is not a
311 # cheap import Since it is mainly used in test suits, we lazy import it
312 # here to save on the order of 10 ms of import time for most users
313 #
314 # The previous way Tester was imported also had a side effect of adding
315 # the full `numpy.testing` namespace
316 if attr == 'testing':
317 import numpy.testing as testing
318 return testing
319 elif attr == 'Tester':
320 from .testing import Tester
321 return Tester
323 raise AttributeError("module {!r} has no attribute "
324 "{!r}".format(__name__, attr))
326 def __dir__():
327 public_symbols = globals().keys() | {'Tester', 'testing'}
328 public_symbols -= {
329 "core", "matrixlib",
330 # These were moved in 1.25 and may be deprecated eventually:
331 "ModuleDeprecationWarning", "VisibleDeprecationWarning",
332 "ComplexWarning", "TooHardError", "AxisError"
333 }
334 return list(public_symbols)
336 # Pytest testing
337 from numpy._pytesttester import PytestTester
338 test = PytestTester(__name__)
339 del PytestTester
341 def _sanity_check():
342 """
343 Quick sanity checks for common bugs caused by environment.
344 There are some cases e.g. with wrong BLAS ABI that cause wrong
345 results under specific runtime conditions that are not necessarily
346 achieved during test suite runs, and it is useful to catch those early.
348 See https://github.com/numpy/numpy/issues/8577 and other
349 similar bug reports.
351 """
352 try:
353 x = ones(2, dtype=float32)
354 if not abs(x.dot(x) - float32(2.0)) < 1e-5:
355 raise AssertionError()
356 except AssertionError:
357 msg = ("The current Numpy installation ({!r}) fails to "
358 "pass simple sanity checks. This can be caused for example "
359 "by incorrect BLAS library being linked in, or by mixing "
360 "package managers (pip, conda, apt, ...). Search closed "
361 "numpy issues for similar problems.")
362 raise RuntimeError(msg.format(__file__)) from None
364 _sanity_check()
365 del _sanity_check
367 def _mac_os_check():
368 """
369 Quick Sanity check for Mac OS look for accelerate build bugs.
370 Testing numpy polyfit calls init_dgelsd(LAPACK)
371 """
372 try:
373 c = array([3., 2., 1.])
374 x = linspace(0, 2, 5)
375 y = polyval(c, x)
376 _ = polyfit(x, y, 2, cov=True)
377 except ValueError:
378 pass
380 if sys.platform == "darwin":
381 with warnings.catch_warnings(record=True) as w:
382 _mac_os_check()
383 # Throw runtime error, if the test failed Check for warning and error_message
384 error_message = ""
385 if len(w) > 0:
386 error_message = "{}: {}".format(w[-1].category.__name__, str(w[-1].message))
387 msg = (
388 "Polyfit sanity test emitted a warning, most likely due "
389 "to using a buggy Accelerate backend."
390 "\nIf you compiled yourself, more information is available at:"
391 "\nhttps://numpy.org/doc/stable/user/building.html#accelerated-blas-lapack-libraries"
392 "\nOtherwise report this to the vendor "
393 "that provided NumPy.\n{}\n".format(error_message))
394 raise RuntimeError(msg)
395 del _mac_os_check
397 # We usually use madvise hugepages support, but on some old kernels it
398 # is slow and thus better avoided.
399 # Specifically kernel version 4.6 had a bug fix which probably fixed this:
400 # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
401 import os
402 use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
403 if sys.platform == "linux" and use_hugepage is None:
404 # If there is an issue with parsing the kernel version,
405 # set use_hugepages to 0. Usage of LooseVersion will handle
406 # the kernel version parsing better, but avoided since it
407 # will increase the import time. See: #16679 for related discussion.
408 try:
409 use_hugepage = 1
410 kernel_version = os.uname().release.split(".")[:2]
411 kernel_version = tuple(int(v) for v in kernel_version)
412 if kernel_version < (4, 6):
413 use_hugepage = 0
414 except ValueError:
415 use_hugepages = 0
416 elif use_hugepage is None:
417 # This is not Linux, so it should not matter, just enable anyway
418 use_hugepage = 1
419 else:
420 use_hugepage = int(use_hugepage)
422 # Note that this will currently only make a difference on Linux
423 core.multiarray._set_madvise_hugepage(use_hugepage)
425 # Give a warning if NumPy is reloaded or imported on a sub-interpreter
426 # We do this from python, since the C-module may not be reloaded and
427 # it is tidier organized.
428 core.multiarray._multiarray_umath._reload_guard()
430 core._set_promotion_state(os.environ.get("NPY_PROMOTION_STATE", "legacy"))
432 # Tell PyInstaller where to find hook-numpy.py
433 def _pyinstaller_hooks_dir():
434 from pathlib import Path
435 return [str(Path(__file__).with_name("_pyinstaller").resolve())]
437 # Remove symbols imported for internal use
438 del os
441# get the version using versioneer
442from .version import __version__, git_revision as __git_version__
444# Remove symbols imported for internal use
445del sys, warnings