__init__.py 25 KB

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