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