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