Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/numpy/__init__.py: 9%

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

201 statements  

1""" 

2NumPy 

3===== 

4 

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 

9 

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>`_. 

15 

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. 

20 

21The docstring examples assume that `numpy` has been imported as ``np``:: 

22 

23 >>> import numpy as np 

24 

25Code snippets are indicated by three greater-than signs:: 

26 

27 >>> x = 42 

28 >>> x = x + 1 

29 

30Use the built-in ``help`` function to view a function's docstring:: 

31 

32 >>> help(np.sort) 

33 ... # doctest: +SKIP 

34 

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. 

40 

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) 

58 

59Utilities 

60--------- 

61test 

62 Run numpy unittests 

63show_config 

64 Show numpy build configuration 

65__version__ 

66 NumPy version string 

67 

68Viewing documentation using IPython 

69----------------------------------- 

70 

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). 

79 

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. 

86 

87""" 

88import os 

89import sys 

90import warnings 

91 

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__ 

97 

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 

104 

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 

110 

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 

121 

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 ) 

447 

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 

456 

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 intersect1d, 

463 isin, 

464 setdiff1d, 

465 setxor1d, 

466 union1d, 

467 unique, 

468 unique_all, 

469 unique_counts, 

470 unique_inverse, 

471 unique_values, 

472 ) 

473 from .lib._function_base_impl import ( 

474 angle, 

475 append, 

476 asarray_chkfinite, 

477 average, 

478 bartlett, 

479 bincount, 

480 blackman, 

481 copy, 

482 corrcoef, 

483 cov, 

484 delete, 

485 diff, 

486 digitize, 

487 extract, 

488 flip, 

489 gradient, 

490 hamming, 

491 hanning, 

492 i0, 

493 insert, 

494 interp, 

495 iterable, 

496 kaiser, 

497 median, 

498 meshgrid, 

499 percentile, 

500 piecewise, 

501 place, 

502 quantile, 

503 rot90, 

504 select, 

505 sinc, 

506 sort_complex, 

507 trapezoid, 

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 

625 

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 } 

635 

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") 

645 

646 _specific_msg = ( 

647 "If you specifically wanted the numpy scalar type, use `np.{}` here.") 

648 

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.") 

654 

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"))] 

661 

662 __former_attrs__ = { 

663 n: _msg.format(n=n, extended_msg=extended_msg) 

664 for n, extended_msg in _type_info 

665 } 

666 

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"} 

673 

674 __array_api_version__ = "2024.12" 

675 

676 from ._array_api_info import __array_namespace_info__ 

677 

678 __all__ = list( 

679 __numpy_submodules__ | 

680 set(_core.__all__) | 

681 set(_mat.__all__) | 

682 set(lib._histograms_impl.__all__) | 

683 set(lib._nanfunctions_impl.__all__) | 

684 set(lib._function_base_impl.__all__) | 

685 set(lib._twodim_base_impl.__all__) | 

686 set(lib._shape_base_impl.__all__) | 

687 set(lib._type_check_impl.__all__) | 

688 set(lib._arraysetops_impl.__all__) | 

689 set(lib._ufunclike_impl.__all__) | 

690 set(lib._arraypad_impl.__all__) | 

691 set(lib._utils_impl.__all__) | 

692 set(lib._stride_tricks_impl.__all__) | 

693 set(lib._polynomial_impl.__all__) | 

694 set(lib._npyio_impl.__all__) | 

695 set(lib._index_tricks_impl.__all__) | 

696 {"emath", "show_config", "__version__", "__array_namespace_info__"} 

697 ) 

698 

699 # Filter out Cython harmless warnings 

700 warnings.filterwarnings("ignore", message="numpy.dtype size changed") 

701 warnings.filterwarnings("ignore", message="numpy.ufunc size changed") 

702 warnings.filterwarnings("ignore", message="numpy.ndarray size changed") 

703 

704 def __getattr__(attr): 

705 # Warn for expired attributes 

706 import warnings 

707 

708 if attr == "linalg": 

709 import numpy.linalg as linalg 

710 return linalg 

711 elif attr == "fft": 

712 import numpy.fft as fft 

713 return fft 

714 elif attr == "dtypes": 

715 import numpy.dtypes as dtypes 

716 return dtypes 

717 elif attr == "random": 

718 import numpy.random as random 

719 return random 

720 elif attr == "polynomial": 

721 import numpy.polynomial as polynomial 

722 return polynomial 

723 elif attr == "ma": 

724 import numpy.ma as ma 

725 return ma 

726 elif attr == "ctypeslib": 

727 import numpy.ctypeslib as ctypeslib 

728 return ctypeslib 

729 elif attr == "exceptions": 

730 import numpy.exceptions as exceptions 

731 return exceptions 

732 elif attr == "testing": 

733 import numpy.testing as testing 

734 return testing 

735 elif attr == "matlib": 

736 import numpy.matlib as matlib 

737 return matlib 

738 elif attr == "f2py": 

739 import numpy.f2py as f2py 

740 return f2py 

741 elif attr == "typing": 

742 import numpy.typing as typing 

743 return typing 

744 elif attr == "rec": 

745 import numpy.rec as rec 

746 return rec 

747 elif attr == "char": 

748 import numpy.char as char 

749 return char 

750 elif attr == "array_api": 

751 raise AttributeError("`numpy.array_api` is not available from " 

752 "numpy 2.0 onwards", name=None) 

753 elif attr == "core": 

754 import numpy.core as core 

755 return core 

756 elif attr == "strings": 

757 import numpy.strings as strings 

758 return strings 

759 elif attr == "distutils": 

760 if 'distutils' in __numpy_submodules__: 

761 import numpy.distutils as distutils 

762 return distutils 

763 else: 

764 raise AttributeError("`numpy.distutils` is not available from " 

765 "Python 3.12 onwards", name=None) 

766 

767 if attr in __future_scalars__: 

768 # And future warnings for those that will change, but also give 

769 # the AttributeError 

770 warnings.warn( 

771 f"In the future `np.{attr}` will be defined as the " 

772 "corresponding NumPy scalar.", FutureWarning, stacklevel=2) 

773 

774 if attr in __former_attrs__: 

775 raise AttributeError(__former_attrs__[attr], name=None) 

776 

777 if attr in __expired_attributes__: 

778 raise AttributeError( 

779 f"`np.{attr}` was removed in the NumPy 2.0 release. " 

780 f"{__expired_attributes__[attr]}", 

781 name=None 

782 ) 

783 

784 if attr == "chararray": 

785 warnings.warn( 

786 "`np.chararray` is deprecated and will be removed from " 

787 "the main namespace in the future. Use an array with a string " 

788 "or bytes dtype instead.", DeprecationWarning, stacklevel=2) 

789 import numpy.char as char 

790 return char.chararray 

791 

792 raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") 

793 

794 def __dir__(): 

795 public_symbols = ( 

796 globals().keys() | __numpy_submodules__ 

797 ) 

798 public_symbols -= { 

799 "matrixlib", "matlib", "tests", "conftest", "version", 

800 "distutils", "array_api" 

801 } 

802 return list(public_symbols) 

803 

804 # Pytest testing 

805 from numpy._pytesttester import PytestTester 

806 test = PytestTester(__name__) 

807 del PytestTester 

808 

809 def _sanity_check(): 

810 """ 

811 Quick sanity checks for common bugs caused by environment. 

812 There are some cases e.g. with wrong BLAS ABI that cause wrong 

813 results under specific runtime conditions that are not necessarily 

814 achieved during test suite runs, and it is useful to catch those early. 

815 

816 See https://github.com/numpy/numpy/issues/8577 and other 

817 similar bug reports. 

818 

819 """ 

820 try: 

821 x = ones(2, dtype=float32) 

822 if not abs(x.dot(x) - float32(2.0)) < 1e-5: 

823 raise AssertionError 

824 except AssertionError: 

825 msg = ("The current Numpy installation ({!r}) fails to " 

826 "pass simple sanity checks. This can be caused for example " 

827 "by incorrect BLAS library being linked in, or by mixing " 

828 "package managers (pip, conda, apt, ...). Search closed " 

829 "numpy issues for similar problems.") 

830 raise RuntimeError(msg.format(__file__)) from None 

831 

832 _sanity_check() 

833 del _sanity_check 

834 

835 def _mac_os_check(): 

836 """ 

837 Quick Sanity check for Mac OS look for accelerate build bugs. 

838 Testing numpy polyfit calls init_dgelsd(LAPACK) 

839 """ 

840 try: 

841 c = array([3., 2., 1.]) 

842 x = linspace(0, 2, 5) 

843 y = polyval(c, x) 

844 _ = polyfit(x, y, 2, cov=True) 

845 except ValueError: 

846 pass 

847 

848 if sys.platform == "darwin": 

849 from . import exceptions 

850 with warnings.catch_warnings(record=True) as w: 

851 _mac_os_check() 

852 # Throw runtime error, if the test failed 

853 # Check for warning and report the error_message 

854 if len(w) > 0: 

855 for _wn in w: 

856 if _wn.category is exceptions.RankWarning: 

857 # Ignore other warnings, they may not be relevant (see gh-25433) 

858 error_message = ( 

859 f"{_wn.category.__name__}: {_wn.message}" 

860 ) 

861 msg = ( 

862 "Polyfit sanity test emitted a warning, most likely due " 

863 "to using a buggy Accelerate backend." 

864 "\nIf you compiled yourself, more information is available at:" # noqa: E501 

865 "\nhttps://numpy.org/devdocs/building/index.html" 

866 "\nOtherwise report this to the vendor " 

867 f"that provided NumPy.\n\n{error_message}\n") 

868 raise RuntimeError(msg) 

869 del _wn 

870 del w 

871 del _mac_os_check 

872 

873 def blas_fpe_check(): 

874 # Check if BLAS adds spurious FPEs, mostly seen on M4 arms with Accelerate. 

875 with errstate(all='raise'): 

876 x = ones((20, 20)) 

877 try: 

878 x @ x 

879 except FloatingPointError: 

880 res = _core._multiarray_umath._blas_supports_fpe(False) 

881 if res: # res was not modified (hardcoded to True for now) 

882 warnings.warn( 

883 "Spurious warnings given by blas but suppression not " 

884 "set up on this platform. Please open a NumPy issue.", 

885 UserWarning, stacklevel=2) 

886 

887 blas_fpe_check() 

888 del blas_fpe_check 

889 

890 def hugepage_setup(): 

891 """ 

892 We usually use madvise hugepages support, but on some old kernels it 

893 is slow and thus better avoided. Specifically kernel version 4.6 

894 had a bug fix which probably fixed this: 

895 https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff 

896 """ 

897 use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None) 

898 if sys.platform == "linux" and use_hugepage is None: 

899 # If there is an issue with parsing the kernel version, 

900 # set use_hugepage to 0. Usage of LooseVersion will handle 

901 # the kernel version parsing better, but avoided since it 

902 # will increase the import time. 

903 # See: #16679 for related discussion. 

904 try: 

905 use_hugepage = 1 

906 kernel_version = os.uname().release.split(".")[:2] 

907 kernel_version = tuple(int(v) for v in kernel_version) 

908 if kernel_version < (4, 6): 

909 use_hugepage = 0 

910 except ValueError: 

911 use_hugepage = 0 

912 elif use_hugepage is None: 

913 # This is not Linux, so it should not matter, just enable anyway 

914 use_hugepage = 1 

915 else: 

916 use_hugepage = int(use_hugepage) 

917 return use_hugepage 

918 

919 # Note that this will currently only make a difference on Linux 

920 _core.multiarray._set_madvise_hugepage(hugepage_setup()) 

921 del hugepage_setup 

922 

923 # Give a warning if NumPy is reloaded or imported on a sub-interpreter 

924 # We do this from python, since the C-module may not be reloaded and 

925 # it is tidier organized. 

926 _core.multiarray._multiarray_umath._reload_guard() 

927 

928 # TODO: Remove the environment variable entirely now that it is "weak" 

929 if (os.environ.get("NPY_PROMOTION_STATE", "weak") != "weak"): 

930 warnings.warn( 

931 "NPY_PROMOTION_STATE was a temporary feature for NumPy 2.0 " 

932 "transition and is ignored after NumPy 2.2.", 

933 UserWarning, stacklevel=2) 

934 

935 # Tell PyInstaller where to find hook-numpy.py 

936 def _pyinstaller_hooks_dir(): 

937 from pathlib import Path 

938 return [str(Path(__file__).with_name("_pyinstaller").resolve())] 

939 

940 

941# Remove symbols imported for internal use 

942del os, sys, warnings