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

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

89 statements  

1""" 

2Contains the core of NumPy: ndarray, ufuncs, dtypes, etc. 

3 

4Please note that this module is private. All functions and objects 

5are available in the main ``numpy`` namespace - use that instead. 

6 

7""" 

8 

9import os 

10 

11from numpy.version import version as __version__ 

12 

13# disables OpenBLAS affinity setting of the main thread that limits 

14# python threads or processes to one core 

15env_added = [] 

16for envkey in ['OPENBLAS_MAIN_FREE']: 

17 if envkey not in os.environ: 

18 # Note: using `putenv` (and `unsetenv` further down) instead of updating 

19 # `os.environ` on purpose to avoid a race condition, see gh-30627. 

20 os.putenv(envkey, '1') 

21 env_added.append(envkey) 

22 

23try: 

24 from . import multiarray 

25except ImportError as exc: 

26 import sys 

27 

28 # Bypass for the module re-initialization opt-out 

29 if exc.msg == "cannot load module more than once per process": 

30 raise 

31 

32 # Basically always, the problem should be that the C module is wrong/missing... 

33 if ( 

34 isinstance(exc, ModuleNotFoundError) 

35 and exc.name == "numpy._core._multiarray_umath" 

36 ): 

37 import sys 

38 candidates = [] 

39 for path in __path__: 

40 candidates.extend( 

41 f for f in os.listdir(path) if f.startswith("_multiarray_umath")) 

42 if len(candidates) == 0: 

43 bad_c_module_info = ( 

44 "We found no compiled module, did NumPy build successfully?\n") 

45 else: 

46 candidate_str = '\n * '.join(candidates) 

47 # cache_tag is documented to be possibly None, so just use name if it is 

48 # this guesses at cache_tag being the same as the extension module scheme 

49 tag = sys.implementation.cache_tag or sys.implementation.name 

50 bad_c_module_info = ( 

51 f"The following compiled module files exist, but seem incompatible\n" 

52 f"with with either python '{tag}' or the " 

53 f"platform '{sys.platform}':\n\n * {candidate_str}\n" 

54 ) 

55 else: 

56 bad_c_module_info = "" 

57 

58 major, minor, *_ = sys.version_info 

59 msg = f""" 

60 

61IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! 

62 

63Importing the numpy C-extensions failed. This error can happen for 

64many reasons, often due to issues with your setup or how NumPy was 

65installed. 

66{bad_c_module_info} 

67We have compiled some common reasons and troubleshooting tips at: 

68 

69 https://numpy.org/devdocs/user/troubleshooting-importerror.html 

70 

71Please note and check the following: 

72 

73 * The Python version is: Python {major}.{minor} from "{sys.executable}" 

74 * The NumPy version is: "{__version__}" 

75 

76and make sure that they are the versions you expect. 

77 

78Please carefully study the information and documentation linked above. 

79This is unlikely to be a NumPy issue but will be caused by a bad install 

80or environment on your machine. 

81 

82Original error was: {exc} 

83""" 

84 

85 raise ImportError(msg) from exc 

86finally: 

87 for envkey in env_added: 

88 os.unsetenv(envkey) 

89del envkey 

90del env_added 

91del os 

92 

93from . import umath 

94 

95# Check that multiarray,umath are pure python modules wrapping 

96# _multiarray_umath and not either of the old c-extension modules 

97if not (hasattr(multiarray, '_multiarray_umath') and 

98 hasattr(umath, '_multiarray_umath')): 

99 import sys 

100 path = sys.modules['numpy'].__path__ 

101 msg = ("Something is wrong with the numpy installation. " 

102 "While importing we detected an older version of " 

103 "numpy in {}. One method of fixing this is to repeatedly uninstall " 

104 "numpy until none is found, then reinstall this version.") 

105 raise ImportError(msg.format(path)) 

106 

107from . import numerictypes as nt 

108from .numerictypes import sctypeDict, sctypes 

109 

110multiarray.set_typeDict(nt.sctypeDict) 

111from . import einsumfunc, fromnumeric, function_base, getlimits, numeric, shape_base 

112from .einsumfunc import * 

113from .fromnumeric import * 

114from .function_base import * 

115from .getlimits import * 

116 

117# Note: module name memmap is overwritten by a class with same name 

118from .memmap import * 

119from .numeric import * 

120from .records import recarray, record 

121from .shape_base import * 

122 

123del nt 

124 

125# do this after everything else, to minimize the chance of this misleadingly 

126# appearing in an import-time traceback 

127# add these for module-freeze analysis (like PyInstaller) 

128from . import ( 

129 _add_newdocs, 

130 _add_newdocs_scalars, 

131 _dtype, 

132 _dtype_ctypes, 

133 _internal, 

134 _methods, 

135) 

136from .numeric import absolute as abs 

137 

138acos = numeric.arccos 

139acosh = numeric.arccosh 

140asin = numeric.arcsin 

141asinh = numeric.arcsinh 

142atan = numeric.arctan 

143atanh = numeric.arctanh 

144atan2 = numeric.arctan2 

145concat = numeric.concatenate 

146bitwise_left_shift = numeric.left_shift 

147bitwise_invert = numeric.invert 

148bitwise_right_shift = numeric.right_shift 

149permute_dims = numeric.transpose 

150pow = numeric.power 

151 

152__all__ = [ 

153 "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2", 

154 "bitwise_invert", "bitwise_left_shift", "bitwise_right_shift", "concat", 

155 "pow", "permute_dims", "memmap", "sctypeDict", "record", "recarray" 

156] 

157__all__ += numeric.__all__ 

158__all__ += function_base.__all__ 

159__all__ += getlimits.__all__ 

160__all__ += shape_base.__all__ 

161__all__ += einsumfunc.__all__ 

162 

163 

164def _ufunc_reduce(func): 

165 # Report the `__name__`. pickle will try to find the module. Note that 

166 # pickle supports for this `__name__` to be a `__qualname__`. It may 

167 # make sense to add a `__qualname__` to ufuncs, to allow this more 

168 # explicitly (Numba has ufuncs as attributes). 

169 # See also: https://github.com/dask/distributed/issues/3450 

170 return func.__name__ 

171 

172 

173def _DType_reconstruct(scalar_type): 

174 # This is a work-around to pickle type(np.dtype(np.float64)), etc. 

175 # and it should eventually be replaced with a better solution, e.g. when 

176 # DTypes become HeapTypes. 

177 return type(dtype(scalar_type)) 

178 

179 

180def _DType_reduce(DType): 

181 # As types/classes, most DTypes can simply be pickled by their name: 

182 if not DType._legacy or DType.__module__ == "numpy.dtypes": 

183 return DType.__name__ 

184 

185 # However, user defined legacy dtypes (like rational) do not end up in 

186 # `numpy.dtypes` as module and do not have a public class at all. 

187 # For these, we pickle them by reconstructing them from the scalar type: 

188 scalar_type = DType.type 

189 return _DType_reconstruct, (scalar_type,) 

190 

191 

192import copyreg 

193 

194copyreg.pickle(ufunc, _ufunc_reduce) 

195copyreg.pickle(type(dtype), _DType_reduce, _DType_reconstruct) 

196 

197# Unclutter namespace (must keep _*_reconstruct for unpickling) 

198del copyreg, _ufunc_reduce, _DType_reduce 

199 

200from numpy._pytesttester import PytestTester 

201 

202test = PytestTester(__name__) 

203del PytestTester