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, matrixlib as _mat
458 from .lib import scimath as emath
459 from .lib._arraypad_impl import pad
460 from .lib._arraysetops_impl import (
461 ediff1d,
462 in1d,
463 intersect1d,
464 isin,
465 setdiff1d,
466 setxor1d,
467 union1d,
468 unique,
469 unique_all,
470 unique_counts,
471 unique_inverse,
472 unique_values,
473 )
474 from .lib._function_base_impl import (
475 angle,
476 append,
477 asarray_chkfinite,
478 average,
479 bartlett,
480 bincount,
481 blackman,
482 copy,
483 corrcoef,
484 cov,
485 delete,
486 diff,
487 digitize,
488 extract,
489 flip,
490 gradient,
491 hamming,
492 hanning,
493 i0,
494 insert,
495 interp,
496 iterable,
497 kaiser,
498 median,
499 meshgrid,
500 percentile,
501 piecewise,
502 place,
503 quantile,
504 rot90,
505 select,
506 sinc,
507 sort_complex,
508 trapezoid,
509 trapz,
510 trim_zeros,
511 unwrap,
512 vectorize,
513 )
514 from .lib._histograms_impl import histogram, histogram_bin_edges, histogramdd
515 from .lib._index_tricks_impl import (
516 c_,
517 diag_indices,
518 diag_indices_from,
519 fill_diagonal,
520 index_exp,
521 ix_,
522 mgrid,
523 ndenumerate,
524 ndindex,
525 ogrid,
526 r_,
527 ravel_multi_index,
528 s_,
529 unravel_index,
530 )
531 from .lib._nanfunctions_impl import (
532 nanargmax,
533 nanargmin,
534 nancumprod,
535 nancumsum,
536 nanmax,
537 nanmean,
538 nanmedian,
539 nanmin,
540 nanpercentile,
541 nanprod,
542 nanquantile,
543 nanstd,
544 nansum,
545 nanvar,
546 )
547 from .lib._npyio_impl import (
548 fromregex,
549 genfromtxt,
550 load,
551 loadtxt,
552 packbits,
553 save,
554 savetxt,
555 savez,
556 savez_compressed,
557 unpackbits,
558 )
559 from .lib._polynomial_impl import (
560 poly,
561 poly1d,
562 polyadd,
563 polyder,
564 polydiv,
565 polyfit,
566 polyint,
567 polymul,
568 polysub,
569 polyval,
570 roots,
571 )
572 from .lib._shape_base_impl import (
573 apply_along_axis,
574 apply_over_axes,
575 array_split,
576 column_stack,
577 dsplit,
578 dstack,
579 expand_dims,
580 hsplit,
581 kron,
582 put_along_axis,
583 row_stack,
584 split,
585 take_along_axis,
586 tile,
587 vsplit,
588 )
589 from .lib._stride_tricks_impl import (
590 broadcast_arrays,
591 broadcast_shapes,
592 broadcast_to,
593 )
594 from .lib._twodim_base_impl import (
595 diag,
596 diagflat,
597 eye,
598 fliplr,
599 flipud,
600 histogram2d,
601 mask_indices,
602 tri,
603 tril,
604 tril_indices,
605 tril_indices_from,
606 triu,
607 triu_indices,
608 triu_indices_from,
609 vander,
610 )
611 from .lib._type_check_impl import (
612 common_type,
613 imag,
614 iscomplex,
615 iscomplexobj,
616 isreal,
617 isrealobj,
618 mintypecode,
619 nan_to_num,
620 real,
621 real_if_close,
622 typename,
623 )
624 from .lib._ufunclike_impl import fix, isneginf, isposinf
625 from .lib._utils_impl import get_include, info, show_runtime
626 from .matrixlib import asmatrix, bmat, matrix
628 # public submodules are imported lazily, therefore are accessible from
629 # __getattr__. Note that `distutils` (deprecated) and `array_api`
630 # (experimental label) are not added here, because `from numpy import *`
631 # must not raise any warnings - that's too disruptive.
632 __numpy_submodules__ = {
633 "linalg", "fft", "dtypes", "random", "polynomial", "ma",
634 "exceptions", "lib", "ctypeslib", "testing", "typing",
635 "f2py", "test", "rec", "char", "core", "strings",
636 }
638 # We build warning messages for former attributes
639 _msg = (
640 "module 'numpy' has no attribute '{n}'.\n"
641 "`np.{n}` was a deprecated alias for the builtin `{n}`. "
642 "To avoid this error in existing code, use `{n}` by itself. "
643 "Doing this will not modify any behavior and is safe. {extended_msg}\n"
644 "The aliases was originally deprecated in NumPy 1.20; for more "
645 "details and guidance see the original release note at:\n"
646 " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
648 _specific_msg = (
649 "If you specifically wanted the numpy scalar type, use `np.{}` here.")
651 _int_extended_msg = (
652 "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
653 "or `np.int32` to specify the precision. If you wish to review "
654 "your current use, check the release note link for "
655 "additional information.")
657 _type_info = [
658 ("object", ""), # The NumPy scalar only exists by name.
659 ("float", _specific_msg.format("float64")),
660 ("complex", _specific_msg.format("complex128")),
661 ("str", _specific_msg.format("str_")),
662 ("int", _int_extended_msg.format("int"))]
664 __former_attrs__ = {
665 n: _msg.format(n=n, extended_msg=extended_msg)
666 for n, extended_msg in _type_info
667 }
669 # Some of these could be defined right away, but most were aliases to
670 # the Python objects and only removed in NumPy 1.24. Defining them should
671 # probably wait for NumPy 1.26 or 2.0.
672 # When defined, these should possibly not be added to `__all__` to avoid
673 # import with `from numpy import *`.
674 __future_scalars__ = {"str", "bytes", "object"}
676 __array_api_version__ = "2024.12"
678 from ._array_api_info import __array_namespace_info__
680 # now that numpy core module is imported, can initialize limits
681 _core.getlimits._register_known_types()
683 __all__ = list(
684 __numpy_submodules__ |
685 set(_core.__all__) |
686 set(_mat.__all__) |
687 set(lib._histograms_impl.__all__) |
688 set(lib._nanfunctions_impl.__all__) |
689 set(lib._function_base_impl.__all__) |
690 set(lib._twodim_base_impl.__all__) |
691 set(lib._shape_base_impl.__all__) |
692 set(lib._type_check_impl.__all__) |
693 set(lib._arraysetops_impl.__all__) |
694 set(lib._ufunclike_impl.__all__) |
695 set(lib._arraypad_impl.__all__) |
696 set(lib._utils_impl.__all__) |
697 set(lib._stride_tricks_impl.__all__) |
698 set(lib._polynomial_impl.__all__) |
699 set(lib._npyio_impl.__all__) |
700 set(lib._index_tricks_impl.__all__) |
701 {"emath", "show_config", "__version__", "__array_namespace_info__"}
702 )
704 # Filter out Cython harmless warnings
705 warnings.filterwarnings("ignore", message="numpy.dtype size changed")
706 warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
707 warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
709 def __getattr__(attr):
710 # Warn for expired attributes
711 import warnings
713 if attr == "linalg":
714 import numpy.linalg as linalg
715 return linalg
716 elif attr == "fft":
717 import numpy.fft as fft
718 return fft
719 elif attr == "dtypes":
720 import numpy.dtypes as dtypes
721 return dtypes
722 elif attr == "random":
723 import numpy.random as random
724 return random
725 elif attr == "polynomial":
726 import numpy.polynomial as polynomial
727 return polynomial
728 elif attr == "ma":
729 import numpy.ma as ma
730 return ma
731 elif attr == "ctypeslib":
732 import numpy.ctypeslib as ctypeslib
733 return ctypeslib
734 elif attr == "exceptions":
735 import numpy.exceptions as exceptions
736 return exceptions
737 elif attr == "testing":
738 import numpy.testing as testing
739 return testing
740 elif attr == "matlib":
741 import numpy.matlib as matlib
742 return matlib
743 elif attr == "f2py":
744 import numpy.f2py as f2py
745 return f2py
746 elif attr == "typing":
747 import numpy.typing as typing
748 return typing
749 elif attr == "rec":
750 import numpy.rec as rec
751 return rec
752 elif attr == "char":
753 import numpy.char as char
754 return char
755 elif attr == "array_api":
756 raise AttributeError("`numpy.array_api` is not available from "
757 "numpy 2.0 onwards", name=None)
758 elif attr == "core":
759 import numpy.core as core
760 return core
761 elif attr == "strings":
762 import numpy.strings as strings
763 return strings
764 elif attr == "distutils":
765 if 'distutils' in __numpy_submodules__:
766 import numpy.distutils as distutils
767 return distutils
768 else:
769 raise AttributeError("`numpy.distutils` is not available from "
770 "Python 3.12 onwards", name=None)
772 if attr in __future_scalars__:
773 # And future warnings for those that will change, but also give
774 # the AttributeError
775 warnings.warn(
776 f"In the future `np.{attr}` will be defined as the "
777 "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
779 if attr in __former_attrs__:
780 raise AttributeError(__former_attrs__[attr], name=None)
782 if attr in __expired_attributes__:
783 raise AttributeError(
784 f"`np.{attr}` was removed in the NumPy 2.0 release. "
785 f"{__expired_attributes__[attr]}",
786 name=None
787 )
789 if attr == "chararray":
790 warnings.warn(
791 "`np.chararray` is deprecated and will be removed from "
792 "the main namespace in the future. Use an array with a string "
793 "or bytes dtype instead.", DeprecationWarning, stacklevel=2)
794 import numpy.char as char
795 return char.chararray
797 raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
799 def __dir__():
800 public_symbols = (
801 globals().keys() | __numpy_submodules__
802 )
803 public_symbols -= {
804 "matrixlib", "matlib", "tests", "conftest", "version",
805 "distutils", "array_api"
806 }
807 return list(public_symbols)
809 # Pytest testing
810 from numpy._pytesttester import PytestTester
811 test = PytestTester(__name__)
812 del PytestTester
814 def _sanity_check():
815 """
816 Quick sanity checks for common bugs caused by environment.
817 There are some cases e.g. with wrong BLAS ABI that cause wrong
818 results under specific runtime conditions that are not necessarily
819 achieved during test suite runs, and it is useful to catch those early.
821 See https://github.com/numpy/numpy/issues/8577 and other
822 similar bug reports.
824 """
825 try:
826 x = ones(2, dtype=float32)
827 if not abs(x.dot(x) - float32(2.0)) < 1e-5:
828 raise AssertionError
829 except AssertionError:
830 msg = ("The current Numpy installation ({!r}) fails to "
831 "pass simple sanity checks. This can be caused for example "
832 "by incorrect BLAS library being linked in, or by mixing "
833 "package managers (pip, conda, apt, ...). Search closed "
834 "numpy issues for similar problems.")
835 raise RuntimeError(msg.format(__file__)) from None
837 _sanity_check()
838 del _sanity_check
840 def _mac_os_check():
841 """
842 Quick Sanity check for Mac OS look for accelerate build bugs.
843 Testing numpy polyfit calls init_dgelsd(LAPACK)
844 """
845 try:
846 c = array([3., 2., 1.])
847 x = linspace(0, 2, 5)
848 y = polyval(c, x)
849 _ = polyfit(x, y, 2, cov=True)
850 except ValueError:
851 pass
853 if sys.platform == "darwin":
854 from . import exceptions
855 with warnings.catch_warnings(record=True) as w:
856 _mac_os_check()
857 # Throw runtime error, if the test failed
858 # Check for warning and report the error_message
859 if len(w) > 0:
860 for _wn in w:
861 if _wn.category is exceptions.RankWarning:
862 # Ignore other warnings, they may not be relevant (see gh-25433)
863 error_message = (
864 f"{_wn.category.__name__}: {_wn.message}"
865 )
866 msg = (
867 "Polyfit sanity test emitted a warning, most likely due "
868 "to using a buggy Accelerate backend."
869 "\nIf you compiled yourself, more information is available at:" # noqa: E501
870 "\nhttps://numpy.org/devdocs/building/index.html"
871 "\nOtherwise report this to the vendor "
872 f"that provided NumPy.\n\n{error_message}\n")
873 raise RuntimeError(msg)
874 del _wn
875 del w
876 del _mac_os_check
878 def hugepage_setup():
879 """
880 We usually use madvise hugepages support, but on some old kernels it
881 is slow and thus better avoided. Specifically kernel version 4.6
882 had a bug fix which probably fixed this:
883 https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
884 """
885 use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
886 if sys.platform == "linux" and use_hugepage is None:
887 # If there is an issue with parsing the kernel version,
888 # set use_hugepage to 0. Usage of LooseVersion will handle
889 # the kernel version parsing better, but avoided since it
890 # will increase the import time.
891 # See: #16679 for related discussion.
892 try:
893 use_hugepage = 1
894 kernel_version = os.uname().release.split(".")[:2]
895 kernel_version = tuple(int(v) for v in kernel_version)
896 if kernel_version < (4, 6):
897 use_hugepage = 0
898 except ValueError:
899 use_hugepage = 0
900 elif use_hugepage is None:
901 # This is not Linux, so it should not matter, just enable anyway
902 use_hugepage = 1
903 else:
904 use_hugepage = int(use_hugepage)
905 return use_hugepage
907 # Note that this will currently only make a difference on Linux
908 _core.multiarray._set_madvise_hugepage(hugepage_setup())
909 del hugepage_setup
911 # Give a warning if NumPy is reloaded or imported on a sub-interpreter
912 # We do this from python, since the C-module may not be reloaded and
913 # it is tidier organized.
914 _core.multiarray._multiarray_umath._reload_guard()
916 # TODO: Remove the environment variable entirely now that it is "weak"
917 if (os.environ.get("NPY_PROMOTION_STATE", "weak") != "weak"):
918 warnings.warn(
919 "NPY_PROMOTION_STATE was a temporary feature for NumPy 2.0 "
920 "transition and is ignored after NumPy 2.2.",
921 UserWarning, stacklevel=2)
923 # Tell PyInstaller where to find hook-numpy.py
924 def _pyinstaller_hooks_dir():
925 from pathlib import Path
926 return [str(Path(__file__).with_name("_pyinstaller").resolve())]
929# Remove symbols imported for internal use
930del os, sys, warnings