__init__.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """
  2. Contains the core of NumPy: ndarray, ufuncs, dtypes, etc.
  3. Please note that this module is private. All functions and objects
  4. are available in the main ``numpy`` namespace - use that instead.
  5. """
  6. from numpy.version import version as __version__
  7. import os
  8. import warnings
  9. # disables OpenBLAS affinity setting of the main thread that limits
  10. # python threads or processes to one core
  11. env_added = []
  12. for envkey in ['OPENBLAS_MAIN_FREE', 'GOTOBLAS_MAIN_FREE']:
  13. if envkey not in os.environ:
  14. os.environ[envkey] = '1'
  15. env_added.append(envkey)
  16. try:
  17. from . import multiarray
  18. except ImportError as exc:
  19. import sys
  20. msg = """
  21. IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
  22. Importing the numpy C-extensions failed. This error can happen for
  23. many reasons, often due to issues with your setup or how NumPy was
  24. installed.
  25. We have compiled some common reasons and troubleshooting tips at:
  26. https://numpy.org/devdocs/user/troubleshooting-importerror.html
  27. Please note and check the following:
  28. * The Python version is: Python%d.%d from "%s"
  29. * The NumPy version is: "%s"
  30. and make sure that they are the versions you expect.
  31. Please carefully study the documentation linked above for further help.
  32. Original error was: %s
  33. """ % (sys.version_info[0], sys.version_info[1], sys.executable,
  34. __version__, exc)
  35. raise ImportError(msg)
  36. finally:
  37. for envkey in env_added:
  38. del os.environ[envkey]
  39. del envkey
  40. del env_added
  41. del os
  42. from . import umath
  43. # Check that multiarray,umath are pure python modules wrapping
  44. # _multiarray_umath and not either of the old c-extension modules
  45. if not (hasattr(multiarray, '_multiarray_umath') and
  46. hasattr(umath, '_multiarray_umath')):
  47. import sys
  48. path = sys.modules['numpy'].__path__
  49. msg = ("Something is wrong with the numpy installation. "
  50. "While importing we detected an older version of "
  51. "numpy in {}. One method of fixing this is to repeatedly uninstall "
  52. "numpy until none is found, then reinstall this version.")
  53. raise ImportError(msg.format(path))
  54. from . import numerictypes as nt
  55. multiarray.set_typeDict(nt.sctypeDict)
  56. from . import numeric
  57. from .numeric import *
  58. from . import fromnumeric
  59. from .fromnumeric import *
  60. from . import defchararray as char
  61. from . import records
  62. from . import records as rec
  63. from .records import record, recarray, format_parser
  64. # Note: module name memmap is overwritten by a class with same name
  65. from .memmap import *
  66. from .defchararray import chararray
  67. from . import function_base
  68. from .function_base import *
  69. from . import _machar
  70. from ._machar import *
  71. from . import getlimits
  72. from .getlimits import *
  73. from . import shape_base
  74. from .shape_base import *
  75. from . import einsumfunc
  76. from .einsumfunc import *
  77. del nt
  78. from .fromnumeric import amax as max, amin as min, round_ as round
  79. from .numeric import absolute as abs
  80. # do this after everything else, to minimize the chance of this misleadingly
  81. # appearing in an import-time traceback
  82. from . import _add_newdocs
  83. from . import _add_newdocs_scalars
  84. # add these for module-freeze analysis (like PyInstaller)
  85. from . import _dtype_ctypes
  86. from . import _internal
  87. from . import _dtype
  88. from . import _methods
  89. __all__ = ['char', 'rec', 'memmap']
  90. __all__ += numeric.__all__
  91. __all__ += ['record', 'recarray', 'format_parser']
  92. __all__ += ['chararray']
  93. __all__ += function_base.__all__
  94. __all__ += getlimits.__all__
  95. __all__ += shape_base.__all__
  96. __all__ += einsumfunc.__all__
  97. # We used to use `np.core._ufunc_reconstruct` to unpickle. This is unnecessary,
  98. # but old pickles saved before 1.20 will be using it, and there is no reason
  99. # to break loading them.
  100. def _ufunc_reconstruct(module, name):
  101. # The `fromlist` kwarg is required to ensure that `mod` points to the
  102. # inner-most module rather than the parent package when module name is
  103. # nested. This makes it possible to pickle non-toplevel ufuncs such as
  104. # scipy.special.expit for instance.
  105. mod = __import__(module, fromlist=[name])
  106. return getattr(mod, name)
  107. def _ufunc_reduce(func):
  108. # Report the `__name__`. pickle will try to find the module. Note that
  109. # pickle supports for this `__name__` to be a `__qualname__`. It may
  110. # make sense to add a `__qualname__` to ufuncs, to allow this more
  111. # explicitly (Numba has ufuncs as attributes).
  112. # See also: https://github.com/dask/distributed/issues/3450
  113. return func.__name__
  114. def _DType_reconstruct(scalar_type):
  115. # This is a work-around to pickle type(np.dtype(np.float64)), etc.
  116. # and it should eventually be replaced with a better solution, e.g. when
  117. # DTypes become HeapTypes.
  118. return type(dtype(scalar_type))
  119. def _DType_reduce(DType):
  120. # To pickle a DType without having to add top-level names, pickle the
  121. # scalar type for now (and assume that reconstruction will be possible).
  122. if DType is dtype:
  123. return "dtype" # must pickle `np.dtype` as a singleton.
  124. scalar_type = DType.type # pickle the scalar type for reconstruction
  125. return _DType_reconstruct, (scalar_type,)
  126. def __getattr__(name):
  127. # Deprecated 2021-10-20, NumPy 1.22
  128. if name == "machar":
  129. warnings.warn(
  130. "The `np.core.machar` module is deprecated (NumPy 1.22)",
  131. DeprecationWarning, stacklevel=2,
  132. )
  133. return _machar
  134. raise AttributeError(f"Module {__name__!r} has no attribute {name!r}")
  135. import copyreg
  136. copyreg.pickle(ufunc, _ufunc_reduce)
  137. copyreg.pickle(type(dtype), _DType_reduce, _DType_reconstruct)
  138. # Unclutter namespace (must keep _*_reconstruct for unpickling)
  139. del copyreg
  140. del _ufunc_reduce
  141. del _DType_reduce
  142. from numpy._pytesttester import PytestTester
  143. test = PytestTester(__name__)
  144. del PytestTester