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