Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/numpy/__init__.py: 10%
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.
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
92# If a version with git hash was stored, use that instead
93from . import version
94from ._expired_attrs_2_0 import __expired_attributes__
95from ._globals import _CopyMode, _NoValue
96from .version import __version__
98# We first need to detect if we're being called as part of the numpy setup
99# procedure itself in a reliable manner.
100try:
101 __NUMPY_SETUP__ # noqa: B018
102except NameError:
103 __NUMPY_SETUP__ = False
105if __NUMPY_SETUP__:
106 sys.stderr.write('Running from numpy source directory.\n')
107else:
108 # Allow distributors to run custom init code before importing numpy._core
109 from . import _distributor_init
111 try:
112 from numpy.__config__ import show_config
113 except ImportError as e:
114 msg = """Error importing numpy: you should not try to import numpy from
115 its source directory; please exit the numpy source tree, and relaunch
116 your python interpreter from there."""
117 raise ImportError(msg) from e
119 from . import _core
120 from ._core import (
121 False_,
122 ScalarType,
123 True_,
124 abs,
125 absolute,
126 acos,
127 acosh,
128 add,
129 all,
130 allclose,
131 amax,
132 amin,
133 any,
134 arange,
135 arccos,
136 arccosh,
137 arcsin,
138 arcsinh,
139 arctan,
140 arctan2,
141 arctanh,
142 argmax,
143 argmin,
144 argpartition,
145 argsort,
146 argwhere,
147 around,
148 array,
149 array2string,
150 array_equal,
151 array_equiv,
152 array_repr,
153 array_str,
154 asanyarray,
155 asarray,
156 ascontiguousarray,
157 asfortranarray,
158 asin,
159 asinh,
160 astype,
161 atan,
162 atan2,
163 atanh,
164 atleast_1d,
165 atleast_2d,
166 atleast_3d,
167 base_repr,
168 binary_repr,
169 bitwise_and,
170 bitwise_count,
171 bitwise_invert,
172 bitwise_left_shift,
173 bitwise_not,
174 bitwise_or,
175 bitwise_right_shift,
176 bitwise_xor,
177 block,
178 bool,
179 bool_,
180 broadcast,
181 busday_count,
182 busday_offset,
183 busdaycalendar,
184 byte,
185 bytes_,
186 can_cast,
187 cbrt,
188 cdouble,
189 ceil,
190 character,
191 choose,
192 clip,
193 clongdouble,
194 complex64,
195 complex128,
196 complexfloating,
197 compress,
198 concat,
199 concatenate,
200 conj,
201 conjugate,
202 convolve,
203 copysign,
204 copyto,
205 correlate,
206 cos,
207 cosh,
208 count_nonzero,
209 cross,
210 csingle,
211 cumprod,
212 cumsum,
213 cumulative_prod,
214 cumulative_sum,
215 datetime64,
216 datetime_as_string,
217 datetime_data,
218 deg2rad,
219 degrees,
220 diagonal,
221 divide,
222 divmod,
223 dot,
224 double,
225 dtype,
226 e,
227 einsum,
228 einsum_path,
229 empty,
230 empty_like,
231 equal,
232 errstate,
233 euler_gamma,
234 exp,
235 exp2,
236 expm1,
237 fabs,
238 finfo,
239 flatiter,
240 flatnonzero,
241 flexible,
242 float16,
243 float32,
244 float64,
245 float_power,
246 floating,
247 floor,
248 floor_divide,
249 fmax,
250 fmin,
251 fmod,
252 format_float_positional,
253 format_float_scientific,
254 frexp,
255 from_dlpack,
256 frombuffer,
257 fromfile,
258 fromfunction,
259 fromiter,
260 frompyfunc,
261 fromstring,
262 full,
263 full_like,
264 gcd,
265 generic,
266 geomspace,
267 get_printoptions,
268 getbufsize,
269 geterr,
270 geterrcall,
271 greater,
272 greater_equal,
273 half,
274 heaviside,
275 hstack,
276 hypot,
277 identity,
278 iinfo,
279 indices,
280 inexact,
281 inf,
282 inner,
283 int8,
284 int16,
285 int32,
286 int64,
287 int_,
288 intc,
289 integer,
290 intp,
291 invert,
292 is_busday,
293 isclose,
294 isdtype,
295 isfinite,
296 isfortran,
297 isinf,
298 isnan,
299 isnat,
300 isscalar,
301 issubdtype,
302 lcm,
303 ldexp,
304 left_shift,
305 less,
306 less_equal,
307 lexsort,
308 linspace,
309 little_endian,
310 log,
311 log1p,
312 log2,
313 log10,
314 logaddexp,
315 logaddexp2,
316 logical_and,
317 logical_not,
318 logical_or,
319 logical_xor,
320 logspace,
321 long,
322 longdouble,
323 longlong,
324 matmul,
325 matrix_transpose,
326 matvec,
327 max,
328 maximum,
329 may_share_memory,
330 mean,
331 memmap,
332 min,
333 min_scalar_type,
334 minimum,
335 mod,
336 modf,
337 moveaxis,
338 multiply,
339 nan,
340 ndarray,
341 ndim,
342 nditer,
343 negative,
344 nested_iters,
345 newaxis,
346 nextafter,
347 nonzero,
348 not_equal,
349 number,
350 object_,
351 ones,
352 ones_like,
353 outer,
354 partition,
355 permute_dims,
356 pi,
357 positive,
358 pow,
359 power,
360 printoptions,
361 prod,
362 promote_types,
363 ptp,
364 put,
365 putmask,
366 rad2deg,
367 radians,
368 ravel,
369 recarray,
370 reciprocal,
371 record,
372 remainder,
373 repeat,
374 require,
375 reshape,
376 resize,
377 result_type,
378 right_shift,
379 rint,
380 roll,
381 rollaxis,
382 round,
383 sctypeDict,
384 searchsorted,
385 set_printoptions,
386 setbufsize,
387 seterr,
388 seterrcall,
389 shape,
390 shares_memory,
391 short,
392 sign,
393 signbit,
394 signedinteger,
395 sin,
396 single,
397 sinh,
398 size,
399 sort,
400 spacing,
401 sqrt,
402 square,
403 squeeze,
404 stack,
405 std,
406 str_,
407 subtract,
408 sum,
409 swapaxes,
410 take,
411 tan,
412 tanh,
413 tensordot,
414 timedelta64,
415 trace,
416 transpose,
417 true_divide,
418 trunc,
419 typecodes,
420 ubyte,
421 ufunc,
422 uint,
423 uint8,
424 uint16,
425 uint32,
426 uint64,
427 uintc,
428 uintp,
429 ulong,
430 ulonglong,
431 unsignedinteger,
432 unstack,
433 ushort,
434 var,
435 vdot,
436 vecdot,
437 vecmat,
438 void,
439 vstack,
440 where,
441 zeros,
442 zeros_like,
443 )
445 # NOTE: It's still under discussion whether these aliases
446 # should be removed.
447 for ta in ["float96", "float128", "complex192", "complex256"]:
448 try:
449 globals()[ta] = getattr(_core, ta)
450 except AttributeError:
451 pass
452 del ta
454 from . import lib
455 from . import matrixlib as _mat
456 from .lib import scimath as emath
457 from .lib._arraypad_impl import pad
458 from .lib._arraysetops_impl import (
459 ediff1d,
460 in1d,
461 intersect1d,
462 isin,
463 setdiff1d,
464 setxor1d,
465 union1d,
466 unique,
467 unique_all,
468 unique_counts,
469 unique_inverse,
470 unique_values,
471 )
472 from .lib._function_base_impl import (
473 angle,
474 append,
475 asarray_chkfinite,
476 average,
477 bartlett,
478 bincount,
479 blackman,
480 copy,
481 corrcoef,
482 cov,
483 delete,
484 diff,
485 digitize,
486 extract,
487 flip,
488 gradient,
489 hamming,
490 hanning,
491 i0,
492 insert,
493 interp,
494 iterable,
495 kaiser,
496 median,
497 meshgrid,
498 percentile,
499 piecewise,
500 place,
501 quantile,
502 rot90,
503 select,
504 sinc,
505 sort_complex,
506 trapezoid,
507 trapz,
508 trim_zeros,
509 unwrap,
510 vectorize,
511 )
512 from .lib._histograms_impl import histogram, histogram_bin_edges, histogramdd
513 from .lib._index_tricks_impl import (
514 c_,
515 diag_indices,
516 diag_indices_from,
517 fill_diagonal,
518 index_exp,
519 ix_,
520 mgrid,
521 ndenumerate,
522 ndindex,
523 ogrid,
524 r_,
525 ravel_multi_index,
526 s_,
527 unravel_index,
528 )
529 from .lib._nanfunctions_impl import (
530 nanargmax,
531 nanargmin,
532 nancumprod,
533 nancumsum,
534 nanmax,
535 nanmean,
536 nanmedian,
537 nanmin,
538 nanpercentile,
539 nanprod,
540 nanquantile,
541 nanstd,
542 nansum,
543 nanvar,
544 )
545 from .lib._npyio_impl import (
546 fromregex,
547 genfromtxt,
548 load,
549 loadtxt,
550 packbits,
551 save,
552 savetxt,
553 savez,
554 savez_compressed,
555 unpackbits,
556 )
557 from .lib._polynomial_impl import (
558 poly,
559 poly1d,
560 polyadd,
561 polyder,
562 polydiv,
563 polyfit,
564 polyint,
565 polymul,
566 polysub,
567 polyval,
568 roots,
569 )
570 from .lib._shape_base_impl import (
571 apply_along_axis,
572 apply_over_axes,
573 array_split,
574 column_stack,
575 dsplit,
576 dstack,
577 expand_dims,
578 hsplit,
579 kron,
580 put_along_axis,
581 row_stack,
582 split,
583 take_along_axis,
584 tile,
585 vsplit,
586 )
587 from .lib._stride_tricks_impl import (
588 broadcast_arrays,
589 broadcast_shapes,
590 broadcast_to,
591 )
592 from .lib._twodim_base_impl import (
593 diag,
594 diagflat,
595 eye,
596 fliplr,
597 flipud,
598 histogram2d,
599 mask_indices,
600 tri,
601 tril,
602 tril_indices,
603 tril_indices_from,
604 triu,
605 triu_indices,
606 triu_indices_from,
607 vander,
608 )
609 from .lib._type_check_impl import (
610 common_type,
611 imag,
612 iscomplex,
613 iscomplexobj,
614 isreal,
615 isrealobj,
616 mintypecode,
617 nan_to_num,
618 real,
619 real_if_close,
620 typename,
621 )
622 from .lib._ufunclike_impl import fix, isneginf, isposinf
623 from .lib._utils_impl import get_include, info, show_runtime
624 from .matrixlib import asmatrix, bmat, matrix
626 # public submodules are imported lazily, therefore are accessible from
627 # __getattr__. Note that `distutils` (deprecated) and `array_api`
628 # (experimental label) are not added here, because `from numpy import *`
629 # must not raise any warnings - that's too disruptive.
630 __numpy_submodules__ = {
631 "linalg", "fft", "dtypes", "random", "polynomial", "ma",
632 "exceptions", "lib", "ctypeslib", "testing", "typing",
633 "f2py", "test", "rec", "char", "core", "strings",
634 }
636 # We build warning messages for former attributes
637 _msg = (
638 "module 'numpy' has no attribute '{n}'.\n"
639 "`np.{n}` was a deprecated alias for the builtin `{n}`. "
640 "To avoid this error in existing code, use `{n}` by itself. "
641 "Doing this will not modify any behavior and is safe. {extended_msg}\n"
642 "The aliases was originally deprecated in NumPy 1.20; for more "
643 "details and guidance see the original release note at:\n"
644 " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
646 _specific_msg = (
647 "If you specifically wanted the numpy scalar type, use `np.{}` here.")
649 _int_extended_msg = (
650 "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
651 "or `np.int32` to specify the precision. If you wish to review "
652 "your current use, check the release note link for "
653 "additional information.")
655 _type_info = [
656 ("object", ""), # The NumPy scalar only exists by name.
657 ("float", _specific_msg.format("float64")),
658 ("complex", _specific_msg.format("complex128")),
659 ("str", _specific_msg.format("str_")),
660 ("int", _int_extended_msg.format("int"))]
662 __former_attrs__ = {
663 n: _msg.format(n=n, extended_msg=extended_msg)
664 for n, extended_msg in _type_info
665 }
667 # Some of these could be defined right away, but most were aliases to
668 # the Python objects and only removed in NumPy 1.24. Defining them should
669 # probably wait for NumPy 1.26 or 2.0.
670 # When defined, these should possibly not be added to `__all__` to avoid
671 # import with `from numpy import *`.
672 __future_scalars__ = {"str", "bytes", "object"}
674 __array_api_version__ = "2024.12"
676 from ._array_api_info import __array_namespace_info__
678 # now that numpy core module is imported, can initialize limits
679 _core.getlimits._register_known_types()
681 __all__ = list(
682 __numpy_submodules__ |
683 set(_core.__all__) |
684 set(_mat.__all__) |
685 set(lib._histograms_impl.__all__) |
686 set(lib._nanfunctions_impl.__all__) |
687 set(lib._function_base_impl.__all__) |
688 set(lib._twodim_base_impl.__all__) |
689 set(lib._shape_base_impl.__all__) |
690 set(lib._type_check_impl.__all__) |
691 set(lib._arraysetops_impl.__all__) |
692 set(lib._ufunclike_impl.__all__) |
693 set(lib._arraypad_impl.__all__) |
694 set(lib._utils_impl.__all__) |
695 set(lib._stride_tricks_impl.__all__) |
696 set(lib._polynomial_impl.__all__) |
697 set(lib._npyio_impl.__all__) |
698 set(lib._index_tricks_impl.__all__) |
699 {"emath", "show_config", "__version__", "__array_namespace_info__"}
700 )
702 # Filter out Cython harmless warnings
703 warnings.filterwarnings("ignore", message="numpy.dtype size changed")
704 warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
705 warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
707 def __getattr__(attr):
708 # Warn for expired attributes
709 import warnings
711 if attr == "linalg":
712 import numpy.linalg as linalg
713 return linalg
714 elif attr == "fft":
715 import numpy.fft as fft
716 return fft
717 elif attr == "dtypes":
718 import numpy.dtypes as dtypes
719 return dtypes
720 elif attr == "random":
721 import numpy.random as random
722 return random
723 elif attr == "polynomial":
724 import numpy.polynomial as polynomial
725 return polynomial
726 elif attr == "ma":
727 import numpy.ma as ma
728 return ma
729 elif attr == "ctypeslib":
730 import numpy.ctypeslib as ctypeslib
731 return ctypeslib
732 elif attr == "exceptions":
733 import numpy.exceptions as exceptions
734 return exceptions
735 elif attr == "testing":
736 import numpy.testing as testing
737 return testing
738 elif attr == "matlib":
739 import numpy.matlib as matlib
740 return matlib
741 elif attr == "f2py":
742 import numpy.f2py as f2py
743 return f2py
744 elif attr == "typing":
745 import numpy.typing as typing
746 return typing
747 elif attr == "rec":
748 import numpy.rec as rec
749 return rec
750 elif attr == "char":
751 import numpy.char as char
752 return char
753 elif attr == "array_api":
754 raise AttributeError("`numpy.array_api` is not available from "
755 "numpy 2.0 onwards", name=None)
756 elif attr == "core":
757 import numpy.core as core
758 return core
759 elif attr == "strings":
760 import numpy.strings as strings
761 return strings
762 elif attr == "distutils":
763 if 'distutils' in __numpy_submodules__:
764 import numpy.distutils as distutils
765 return distutils
766 else:
767 raise AttributeError("`numpy.distutils` is not available from "
768 "Python 3.12 onwards", name=None)
770 if attr in __future_scalars__:
771 # And future warnings for those that will change, but also give
772 # the AttributeError
773 warnings.warn(
774 f"In the future `np.{attr}` will be defined as the "
775 "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
777 if attr in __former_attrs__:
778 raise AttributeError(__former_attrs__[attr], name=None)
780 if attr in __expired_attributes__:
781 raise AttributeError(
782 f"`np.{attr}` was removed in the NumPy 2.0 release. "
783 f"{__expired_attributes__[attr]}",
784 name=None
785 )
787 if attr == "chararray":
788 warnings.warn(
789 "`np.chararray` is deprecated and will be removed from "
790 "the main namespace in the future. Use an array with a string "
791 "or bytes dtype instead.", DeprecationWarning, stacklevel=2)
792 import numpy.char as char
793 return char.chararray
795 raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
797 def __dir__():
798 public_symbols = (
799 globals().keys() | __numpy_submodules__
800 )
801 public_symbols -= {
802 "matrixlib", "matlib", "tests", "conftest", "version",
803 "distutils", "array_api"
804 }
805 return list(public_symbols)
807 # Pytest testing
808 from numpy._pytesttester import PytestTester
809 test = PytestTester(__name__)
810 del PytestTester
812 def _sanity_check():
813 """
814 Quick sanity checks for common bugs caused by environment.
815 There are some cases e.g. with wrong BLAS ABI that cause wrong
816 results under specific runtime conditions that are not necessarily
817 achieved during test suite runs, and it is useful to catch those early.
819 See https://github.com/numpy/numpy/issues/8577 and other
820 similar bug reports.
822 """
823 try:
824 x = ones(2, dtype=float32)
825 if not abs(x.dot(x) - float32(2.0)) < 1e-5:
826 raise AssertionError
827 except AssertionError:
828 msg = ("The current Numpy installation ({!r}) fails to "
829 "pass simple sanity checks. This can be caused for example "
830 "by incorrect BLAS library being linked in, or by mixing "
831 "package managers (pip, conda, apt, ...). Search closed "
832 "numpy issues for similar problems.")
833 raise RuntimeError(msg.format(__file__)) from None
835 _sanity_check()
836 del _sanity_check
838 def _mac_os_check():
839 """
840 Quick Sanity check for Mac OS look for accelerate build bugs.
841 Testing numpy polyfit calls init_dgelsd(LAPACK)
842 """
843 try:
844 c = array([3., 2., 1.])
845 x = linspace(0, 2, 5)
846 y = polyval(c, x)
847 _ = polyfit(x, y, 2, cov=True)
848 except ValueError:
849 pass
851 if sys.platform == "darwin":
852 from . import exceptions
853 with warnings.catch_warnings(record=True) as w:
854 _mac_os_check()
855 # Throw runtime error, if the test failed
856 # Check for warning and report the error_message
857 if len(w) > 0:
858 for _wn in w:
859 if _wn.category is exceptions.RankWarning:
860 # Ignore other warnings, they may not be relevant (see gh-25433)
861 error_message = (
862 f"{_wn.category.__name__}: {_wn.message}"
863 )
864 msg = (
865 "Polyfit sanity test emitted a warning, most likely due "
866 "to using a buggy Accelerate backend."
867 "\nIf you compiled yourself, more information is available at:" # noqa: E501
868 "\nhttps://numpy.org/devdocs/building/index.html"
869 "\nOtherwise report this to the vendor "
870 f"that provided NumPy.\n\n{error_message}\n")
871 raise RuntimeError(msg)
872 del _wn
873 del w
874 del _mac_os_check
876 def hugepage_setup():
877 """
878 We usually use madvise hugepages support, but on some old kernels it
879 is slow and thus better avoided. Specifically kernel version 4.6
880 had a bug fix which probably fixed this:
881 https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
882 """
883 use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
884 if sys.platform == "linux" and use_hugepage is None:
885 # If there is an issue with parsing the kernel version,
886 # set use_hugepage to 0. Usage of LooseVersion will handle
887 # the kernel version parsing better, but avoided since it
888 # will increase the import time.
889 # See: #16679 for related discussion.
890 try:
891 use_hugepage = 1
892 kernel_version = os.uname().release.split(".")[:2]
893 kernel_version = tuple(int(v) for v in kernel_version)
894 if kernel_version < (4, 6):
895 use_hugepage = 0
896 except ValueError:
897 use_hugepage = 0
898 elif use_hugepage is None:
899 # This is not Linux, so it should not matter, just enable anyway
900 use_hugepage = 1
901 else:
902 use_hugepage = int(use_hugepage)
903 return use_hugepage
905 # Note that this will currently only make a difference on Linux
906 _core.multiarray._set_madvise_hugepage(hugepage_setup())
907 del hugepage_setup
909 # Give a warning if NumPy is reloaded or imported on a sub-interpreter
910 # We do this from python, since the C-module may not be reloaded and
911 # it is tidier organized.
912 _core.multiarray._multiarray_umath._reload_guard()
914 # TODO: Remove the environment variable entirely now that it is "weak"
915 if (os.environ.get("NPY_PROMOTION_STATE", "weak") != "weak"):
916 warnings.warn(
917 "NPY_PROMOTION_STATE was a temporary feature for NumPy 2.0 "
918 "transition and is ignored after NumPy 2.2.",
919 UserWarning, stacklevel=2)
921 # Tell PyInstaller where to find hook-numpy.py
922 def _pyinstaller_hooks_dir():
923 from pathlib import Path
924 return [str(Path(__file__).with_name("_pyinstaller").resolve())]
927# Remove symbols imported for internal use
928del os, sys, warnings