__init__.py 26 KB

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