Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/__init__.py: 57%
187 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-09 06:12 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-09 06:12 +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.
41Available subpackages
42---------------------
43lib
44 Basic functions used by several sub-packages.
45random
46 Core Random Tools
47linalg
48 Core Linear Algebra Tools
49fft
50 Core FFT routines
51polynomial
52 Polynomial tools
53testing
54 NumPy testing tools
55distutils
56 Enhancements to distutils with support for
57 Fortran compilers support and more (for Python <= 3.11)
59Utilities
60---------
61test
62 Run numpy unittests
63show_config
64 Show numpy build configuration
65__version__
66 NumPy version string
68Viewing documentation using IPython
69-----------------------------------
71Start IPython and import `numpy` usually under the alias ``np``: `import
72numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
73examples into the shell. To see which functions are available in `numpy`,
74type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
75``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
76down the list. To view the docstring for a function, use
77``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
78the source code).
80Copies vs. in-place operation
81-----------------------------
82Most of the functions in `numpy` return a copy of the array argument
83(e.g., `np.sort`). In-place versions of these functions are often
84available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
85Exceptions to this rule are documented.
87"""
88import os
89import sys
90import warnings
92from ._globals import _NoValue, _CopyMode
93from ._expired_attrs_2_0 import __expired_attributes__
96# If a version with git hash was stored, use that instead
97from . import version
98from .version import __version__
100# We first need to detect if we're being called as part of the numpy setup
101# procedure itself in a reliable manner.
102try:
103 __NUMPY_SETUP__
104except NameError:
105 __NUMPY_SETUP__ = False
107if __NUMPY_SETUP__:
108 sys.stderr.write('Running from numpy source directory.\n')
109else:
110 # Allow distributors to run custom init code before importing numpy._core
111 from . import _distributor_init
113 try:
114 from numpy.__config__ import show as show_config
115 except ImportError as e:
116 msg = """Error importing numpy: you should not try to import numpy from
117 its source directory; please exit the numpy source tree, and relaunch
118 your python interpreter from there."""
119 raise ImportError(msg) from e
121 from . import _core
122 from ._core import (
123 False_, ScalarType, True_, _get_promotion_state, _no_nep50_warning,
124 _set_promotion_state, abs, absolute, acos, acosh, add, all, allclose,
125 amax, amin, any, arange, arccos, arccosh, arcsin, arcsinh,
126 arctan, arctan2, arctanh, argmax, argmin, argpartition, argsort,
127 argwhere, around, array, array2string, array_equal, array_equiv,
128 array_repr, array_str, asanyarray, asarray, ascontiguousarray,
129 asfortranarray, asin, asinh, atan, atanh, atan2, astype, atleast_1d,
130 atleast_2d, atleast_3d, base_repr, binary_repr, bitwise_and,
131 bitwise_count, bitwise_invert, bitwise_left_shift, bitwise_not,
132 bitwise_or, bitwise_right_shift, bitwise_xor, block, bool, bool_,
133 broadcast, busday_count, busday_offset, busdaycalendar, byte, bytes_,
134 can_cast, cbrt, cdouble, ceil, character, choose, clip, clongdouble,
135 complex128, complex64, complexfloating, compress, concat, concatenate,
136 conj, conjugate, convolve, copysign, copyto, correlate, cos, cosh,
137 count_nonzero, cross, csingle, cumprod, cumsum,
138 datetime64, datetime_as_string, datetime_data, deg2rad, degrees,
139 diagonal, divide, divmod, dot, double, dtype, e, einsum, einsum_path,
140 empty, empty_like, equal, errstate, euler_gamma, exp, exp2, expm1,
141 fabs, finfo, flatiter, flatnonzero, flexible, float16, float32,
142 float64, float_power, floating, floor, floor_divide, fmax, fmin, fmod,
143 format_float_positional, format_float_scientific, frexp, from_dlpack,
144 frombuffer, fromfile, fromfunction, fromiter, frompyfunc, fromstring,
145 full, full_like, gcd, generic, geomspace, get_printoptions,
146 getbufsize, geterr, geterrcall, greater, greater_equal, half,
147 heaviside, hstack, hypot, identity, iinfo, iinfo, indices, inexact,
148 inf, inner, int16, int32, int64, int8, int_, intc, integer, intp,
149 invert, is_busday, isclose, isdtype, isfinite, isfortran, isinf,
150 isnan, isnat, isscalar, issubdtype, lcm, ldexp, left_shift, less,
151 less_equal, lexsort, linspace, little_endian, log, log10, log1p, log2,
152 logaddexp, logaddexp2, logical_and, logical_not, logical_or,
153 logical_xor, logspace, long, longdouble, longlong, matmul,
154 matrix_transpose, max, maximum, may_share_memory, mean, memmap, min,
155 min_scalar_type, minimum, mod, modf, moveaxis, multiply, nan, ndarray,
156 ndim, nditer, negative, nested_iters, newaxis, nextafter, nonzero,
157 not_equal, number, object_, ones, ones_like, outer, partition,
158 permute_dims, pi, positive, pow, power, printoptions, prod,
159 promote_types, ptp, put, putmask, rad2deg, radians, ravel, recarray,
160 reciprocal, record, remainder, repeat, require, reshape, resize,
161 result_type, right_shift, rint, roll, rollaxis, round, sctypeDict,
162 searchsorted, set_printoptions, setbufsize, seterr, seterrcall, shape,
163 shares_memory, short, sign, signbit, signedinteger, sin, single, sinh,
164 size, sort, spacing, sqrt, square, squeeze, stack, std,
165 str_, subtract, sum, swapaxes, take, tan, tanh, tensordot,
166 timedelta64, trace, transpose, true_divide, trunc, typecodes, ubyte,
167 ufunc, uint, uint16, uint32, uint64, uint8, uintc, uintp, ulong,
168 ulonglong, unsignedinteger, ushort, var, vdot, vecdot, void, vstack,
169 where, zeros, zeros_like
170 )
172 # NOTE: It's still under discussion whether these aliases
173 # should be removed.
174 for ta in ["float96", "float128", "complex192", "complex256"]:
175 try:
176 globals()[ta] = getattr(_core, ta)
177 except AttributeError:
178 pass
179 del ta
181 from . import lib
182 from .lib import scimath as emath
183 from .lib._histograms_impl import (
184 histogram, histogram_bin_edges, histogramdd
185 )
186 from .lib._nanfunctions_impl import (
187 nanargmax, nanargmin, nancumprod, nancumsum, nanmax, nanmean,
188 nanmedian, nanmin, nanpercentile, nanprod, nanquantile, nanstd,
189 nansum, nanvar
190 )
191 from .lib._function_base_impl import (
192 select, piecewise, trim_zeros, copy, iterable, percentile, diff,
193 gradient, angle, unwrap, sort_complex, flip, rot90, extract, place,
194 vectorize, asarray_chkfinite, average, bincount, digitize, cov,
195 corrcoef, median, sinc, hamming, hanning, bartlett, blackman,
196 kaiser, trapezoid, trapz, i0, meshgrid, delete, insert, append,
197 interp, quantile
198 )
199 from .lib._twodim_base_impl import (
200 diag, diagflat, eye, fliplr, flipud, tri, triu, tril, vander,
201 histogram2d, mask_indices, tril_indices, tril_indices_from,
202 triu_indices, triu_indices_from
203 )
204 from .lib._shape_base_impl import (
205 apply_over_axes, apply_along_axis, array_split, column_stack, dsplit,
206 dstack, expand_dims, hsplit, kron, put_along_axis, row_stack, split,
207 take_along_axis, tile, vsplit
208 )
209 from .lib._type_check_impl import (
210 iscomplexobj, isrealobj, imag, iscomplex, isreal, nan_to_num, real,
211 real_if_close, typename, mintypecode, common_type
212 )
213 from .lib._arraysetops_impl import (
214 ediff1d, in1d, intersect1d, isin, setdiff1d, setxor1d, union1d,
215 unique, unique_all, unique_counts, unique_inverse, unique_values
216 )
217 from .lib._ufunclike_impl import fix, isneginf, isposinf
218 from .lib._arraypad_impl import pad
219 from .lib._utils_impl import (
220 show_runtime, get_include, info
221 )
222 from .lib._stride_tricks_impl import (
223 broadcast_arrays, broadcast_shapes, broadcast_to
224 )
225 from .lib._polynomial_impl import (
226 poly, polyint, polyder, polyadd, polysub, polymul, polydiv, polyval,
227 polyfit, poly1d, roots
228 )
229 from .lib._npyio_impl import (
230 savetxt, loadtxt, genfromtxt, load, save, savez, packbits,
231 savez_compressed, unpackbits, fromregex
232 )
233 from .lib._index_tricks_impl import (
234 diag_indices_from, diag_indices, fill_diagonal, ndindex, ndenumerate,
235 ix_, c_, r_, s_, ogrid, mgrid, unravel_index, ravel_multi_index,
236 index_exp
237 )
238 from . import matrixlib as _mat
239 from .matrixlib import (
240 asmatrix, bmat, matrix
241 )
243 # public submodules are imported lazily, therefore are accessible from
244 # __getattr__. Note that `distutils` (deprecated) and `array_api`
245 # (experimental label) are not added here, because `from numpy import *`
246 # must not raise any warnings - that's too disruptive.
247 __numpy_submodules__ = {
248 "linalg", "fft", "dtypes", "random", "polynomial", "ma",
249 "exceptions", "lib", "ctypeslib", "testing", "typing",
250 "f2py", "test", "rec", "char", "core", "strings",
251 }
253 # We build warning messages for former attributes
254 _msg = (
255 "module 'numpy' has no attribute '{n}'.\n"
256 "`np.{n}` was a deprecated alias for the builtin `{n}`. "
257 "To avoid this error in existing code, use `{n}` by itself. "
258 "Doing this will not modify any behavior and is safe. {extended_msg}\n"
259 "The aliases was originally deprecated in NumPy 1.20; for more "
260 "details and guidance see the original release note at:\n"
261 " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
263 _specific_msg = (
264 "If you specifically wanted the numpy scalar type, use `np.{}` here.")
266 _int_extended_msg = (
267 "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
268 "or `np.int32` to specify the precision. If you wish to review "
269 "your current use, check the release note link for "
270 "additional information.")
272 _type_info = [
273 ("object", ""), # The NumPy scalar only exists by name.
274 ("float", _specific_msg.format("float64")),
275 ("complex", _specific_msg.format("complex128")),
276 ("str", _specific_msg.format("str_")),
277 ("int", _int_extended_msg.format("int"))]
279 __former_attrs__ = {
280 n: _msg.format(n=n, extended_msg=extended_msg)
281 for n, extended_msg in _type_info
282 }
285 # Some of these could be defined right away, but most were aliases to
286 # the Python objects and only removed in NumPy 1.24. Defining them should
287 # probably wait for NumPy 1.26 or 2.0.
288 # When defined, these should possibly not be added to `__all__` to avoid
289 # import with `from numpy import *`.
290 __future_scalars__ = {"str", "bytes", "object"}
292 __array_api_version__ = "2022.12"
294 # now that numpy core module is imported, can initialize limits
295 _core.getlimits._register_known_types()
297 __all__ = list(
298 __numpy_submodules__ |
299 set(_core.__all__) |
300 set(_mat.__all__) |
301 set(lib._histograms_impl.__all__) |
302 set(lib._nanfunctions_impl.__all__) |
303 set(lib._function_base_impl.__all__) |
304 set(lib._twodim_base_impl.__all__) |
305 set(lib._shape_base_impl.__all__) |
306 set(lib._type_check_impl.__all__) |
307 set(lib._arraysetops_impl.__all__) |
308 set(lib._ufunclike_impl.__all__) |
309 set(lib._arraypad_impl.__all__) |
310 set(lib._utils_impl.__all__) |
311 set(lib._stride_tricks_impl.__all__) |
312 set(lib._polynomial_impl.__all__) |
313 set(lib._npyio_impl.__all__) |
314 set(lib._index_tricks_impl.__all__) |
315 {"emath", "show_config", "__version__"}
316 )
318 # Filter out Cython harmless warnings
319 warnings.filterwarnings("ignore", message="numpy.dtype size changed")
320 warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
321 warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
323 def __getattr__(attr):
324 # Warn for expired attributes
325 import warnings
327 if attr == "linalg":
328 import numpy.linalg as linalg
329 return linalg
330 elif attr == "fft":
331 import numpy.fft as fft
332 return fft
333 elif attr == "dtypes":
334 import numpy.dtypes as dtypes
335 return dtypes
336 elif attr == "random":
337 import numpy.random as random
338 return random
339 elif attr == "polynomial":
340 import numpy.polynomial as polynomial
341 return polynomial
342 elif attr == "ma":
343 import numpy.ma as ma
344 return ma
345 elif attr == "ctypeslib":
346 import numpy.ctypeslib as ctypeslib
347 return ctypeslib
348 elif attr == "exceptions":
349 import numpy.exceptions as exceptions
350 return exceptions
351 elif attr == "testing":
352 import numpy.testing as testing
353 return testing
354 elif attr == "matlib":
355 import numpy.matlib as matlib
356 return matlib
357 elif attr == "f2py":
358 import numpy.f2py as f2py
359 return f2py
360 elif attr == "typing":
361 import numpy.typing as typing
362 return typing
363 elif attr == "rec":
364 import numpy.rec as rec
365 return rec
366 elif attr == "char":
367 import numpy.char as char
368 return char
369 elif attr == "array_api":
370 raise AttributeError("`numpy.array_api` is not available from "
371 "numpy 2.0 onwards")
372 elif attr == "core":
373 import numpy.core as core
374 return core
375 elif attr == "strings":
376 import numpy.strings as strings
377 return strings
378 elif attr == "distutils":
379 if 'distutils' in __numpy_submodules__:
380 import numpy.distutils as distutils
381 return distutils
382 else:
383 raise AttributeError("`numpy.distutils` is not available from "
384 "Python 3.12 onwards")
386 if attr in __future_scalars__:
387 # And future warnings for those that will change, but also give
388 # the AttributeError
389 warnings.warn(
390 f"In the future `np.{attr}` will be defined as the "
391 "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
393 if attr in __former_attrs__:
394 raise AttributeError(__former_attrs__[attr])
396 if attr in __expired_attributes__:
397 raise AttributeError(
398 f"`np.{attr}` was removed in the NumPy 2.0 release. "
399 f"{__expired_attributes__[attr]}"
400 )
402 if attr == "chararray":
403 warnings.warn(
404 "`np.chararray` is deprecated and will be removed from "
405 "the main namespace in the future. Use an array with a string "
406 "or bytes dtype instead.", DeprecationWarning, stacklevel=2)
407 import numpy.char as char
408 return char.chararray
410 raise AttributeError("module {!r} has no attribute "
411 "{!r}".format(__name__, attr))
413 def __dir__():
414 public_symbols = (
415 globals().keys() | __numpy_submodules__
416 )
417 public_symbols -= {
418 "matrixlib", "matlib", "tests", "conftest", "version",
419 "compat", "distutils", "array_api"
420 }
421 return list(public_symbols)
423 # Pytest testing
424 from numpy._pytesttester import PytestTester
425 test = PytestTester(__name__)
426 del PytestTester
428 def _sanity_check():
429 """
430 Quick sanity checks for common bugs caused by environment.
431 There are some cases e.g. with wrong BLAS ABI that cause wrong
432 results under specific runtime conditions that are not necessarily
433 achieved during test suite runs, and it is useful to catch those early.
435 See https://github.com/numpy/numpy/issues/8577 and other
436 similar bug reports.
438 """
439 try:
440 x = ones(2, dtype=float32)
441 if not abs(x.dot(x) - float32(2.0)) < 1e-5:
442 raise AssertionError()
443 except AssertionError:
444 msg = ("The current Numpy installation ({!r}) fails to "
445 "pass simple sanity checks. This can be caused for example "
446 "by incorrect BLAS library being linked in, or by mixing "
447 "package managers (pip, conda, apt, ...). Search closed "
448 "numpy issues for similar problems.")
449 raise RuntimeError(msg.format(__file__)) from None
451 _sanity_check()
452 del _sanity_check
454 def _mac_os_check():
455 """
456 Quick Sanity check for Mac OS look for accelerate build bugs.
457 Testing numpy polyfit calls init_dgelsd(LAPACK)
458 """
459 try:
460 c = array([3., 2., 1.])
461 x = linspace(0, 2, 5)
462 y = polyval(c, x)
463 _ = polyfit(x, y, 2, cov=True)
464 except ValueError:
465 pass
467 if sys.platform == "darwin":
468 from . import exceptions
469 with warnings.catch_warnings(record=True) as w:
470 _mac_os_check()
471 # Throw runtime error, if the test failed Check for warning and error_message
472 if len(w) > 0:
473 for _wn in w:
474 if _wn.category is exceptions.RankWarning:
475 # Ignore other warnings, they may not be relevant (see gh-25433).
476 error_message = f"{_wn.category.__name__}: {str(_wn.message)}"
477 msg = (
478 "Polyfit sanity test emitted a warning, most likely due "
479 "to using a buggy Accelerate backend."
480 "\nIf you compiled yourself, more information is available at:"
481 "\nhttps://numpy.org/devdocs/building/index.html"
482 "\nOtherwise report this to the vendor "
483 "that provided NumPy.\n\n{}\n".format(error_message))
484 raise RuntimeError(msg)
485 del _wn
486 del w
487 del _mac_os_check
489 def hugepage_setup():
490 """
491 We usually use madvise hugepages support, but on some old kernels it
492 is slow and thus better avoided. Specifically kernel version 4.6
493 had a bug fix which probably fixed this:
494 https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
495 """
496 use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
497 if sys.platform == "linux" and use_hugepage is None:
498 # If there is an issue with parsing the kernel version,
499 # set use_hugepage to 0. Usage of LooseVersion will handle
500 # the kernel version parsing better, but avoided since it
501 # will increase the import time.
502 # See: #16679 for related discussion.
503 try:
504 use_hugepage = 1
505 kernel_version = os.uname().release.split(".")[:2]
506 kernel_version = tuple(int(v) for v in kernel_version)
507 if kernel_version < (4, 6):
508 use_hugepage = 0
509 except ValueError:
510 use_hugepage = 0
511 elif use_hugepage is None:
512 # This is not Linux, so it should not matter, just enable anyway
513 use_hugepage = 1
514 else:
515 use_hugepage = int(use_hugepage)
516 return use_hugepage
518 # Note that this will currently only make a difference on Linux
519 _core.multiarray._set_madvise_hugepage(hugepage_setup())
520 del hugepage_setup
522 # Give a warning if NumPy is reloaded or imported on a sub-interpreter
523 # We do this from python, since the C-module may not be reloaded and
524 # it is tidier organized.
525 _core.multiarray._multiarray_umath._reload_guard()
527 # TODO: Remove the environment variable entirely now that it is "weak"
528 _core._set_promotion_state(
529 os.environ.get("NPY_PROMOTION_STATE", "weak"))
531 # Tell PyInstaller where to find hook-numpy.py
532 def _pyinstaller_hooks_dir():
533 from pathlib import Path
534 return [str(Path(__file__).with_name("_pyinstaller").resolve())]
537# Remove symbols imported for internal use
538del os, sys, warnings