Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2NumPy 

3===== 

4 

5Provides 

6 1. An array object of arbitrary homogeneous items 

7 2. Fast mathematical operations over arrays 

8 3. Linear Algebra, Fourier Transforms, Random Number Generation 

9 

10How to use the documentation 

11---------------------------- 

12Documentation is available in two forms: docstrings provided 

13with the code, and a loose standing reference guide, available from 

14`the NumPy homepage <https://www.scipy.org>`_. 

15 

16We recommend exploring the docstrings using 

17`IPython <https://ipython.org>`_, an advanced Python shell with 

18TAB-completion and introspection capabilities. See below for further 

19instructions. 

20 

21The docstring examples assume that `numpy` has been imported as `np`:: 

22 

23 >>> import numpy as np 

24 

25Code snippets are indicated by three greater-than signs:: 

26 

27 >>> x = 42 

28 >>> x = x + 1 

29 

30Use the built-in ``help`` function to view a function's docstring:: 

31 

32 >>> help(np.sort) 

33 ... # doctest: +SKIP 

34 

35For some objects, ``np.info(obj)`` may provide additional help. This is 

36particularly true if you see the line "Help on ufunc object:" at the top 

37of the help() page. Ufuncs are implemented in C, not Python, for speed. 

38The native Python help() does not know how to view their help, but our 

39np.info() function does. 

40 

41To search for documents containing a keyword, do:: 

42 

43 >>> np.lookfor('keyword') 

44 ... # doctest: +SKIP 

45 

46General-purpose documents like a glossary and help on the basic concepts 

47of numpy are available under the ``doc`` sub-module:: 

48 

49 >>> from numpy import doc 

50 >>> help(doc) 

51 ... # doctest: +SKIP 

52 

53Available subpackages 

54--------------------- 

55doc 

56 Topical documentation on broadcasting, indexing, etc. 

57lib 

58 Basic functions used by several sub-packages. 

59random 

60 Core Random Tools 

61linalg 

62 Core Linear Algebra Tools 

63fft 

64 Core FFT routines 

65polynomial 

66 Polynomial tools 

67testing 

68 NumPy testing tools 

69f2py 

70 Fortran to Python Interface Generator. 

71distutils 

72 Enhancements to distutils with support for 

73 Fortran compilers support and more. 

74 

75Utilities 

76--------- 

77test 

78 Run numpy unittests 

79show_config 

80 Show numpy build configuration 

81dual 

82 Overwrite certain functions with high-performance Scipy tools 

83matlib 

84 Make everything matrices. 

85__version__ 

86 NumPy version string 

87 

88Viewing documentation using IPython 

89----------------------------------- 

90Start IPython with the NumPy profile (``ipython -p numpy``), which will 

91import `numpy` under the alias `np`. Then, use the ``cpaste`` command to 

92paste examples into the shell. To see which functions are available in 

93`numpy`, type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use 

94``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow 

95down the list. To view the docstring for a function, use 

96``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view 

97the source code). 

98 

99Copies vs. in-place operation 

100----------------------------- 

101Most of the functions in `numpy` return a copy of the array argument 

102(e.g., `np.sort`). In-place versions of these functions are often 

103available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. 

104Exceptions to this rule are documented. 

105 

106""" 

107import sys 

108import warnings 

109 

110from ._globals import ModuleDeprecationWarning, VisibleDeprecationWarning 

111from ._globals import _NoValue 

112 

113# We first need to detect if we're being called as part of the numpy setup 

114# procedure itself in a reliable manner. 

115try: 

116 __NUMPY_SETUP__ 

117except NameError: 

118 __NUMPY_SETUP__ = False 

119 

120if __NUMPY_SETUP__: 

121 sys.stderr.write('Running from numpy source directory.\n') 

122else: 

123 try: 

124 from numpy.__config__ import show as show_config 

125 except ImportError: 

126 msg = """Error importing numpy: you should not try to import numpy from 

127 its source directory; please exit the numpy source tree, and relaunch 

128 your python interpreter from there.""" 

129 raise ImportError(msg) 

130 

131 from .version import git_revision as __git_revision__ 

132 from .version import version as __version__ 

133 

134 __all__ = ['ModuleDeprecationWarning', 

135 'VisibleDeprecationWarning'] 

136 

137 # Allow distributors to run custom init code 

138 from . import _distributor_init 

139 

140 from . import core 

141 from .core import * 

142 from . import compat 

143 from . import lib 

144 # NOTE: to be revisited following future namespace cleanup. 

145 # See gh-14454 and gh-15672 for discussion. 

146 from .lib import * 

147 

148 from . import linalg 

149 from . import fft 

150 from . import polynomial 

151 from . import random 

152 from . import ctypeslib 

153 from . import ma 

154 from . import matrixlib as _mat 

155 from .matrixlib import * 

156 

157 # Make these accessible from numpy name-space 

158 # but not imported in from numpy import * 

159 # TODO[gh-6103]: Deprecate these 

160 from builtins import bool, int, float, complex, object, str 

161 from .compat import long, unicode 

162 

163 from .core import round, abs, max, min 

164 # now that numpy modules are imported, can initialize limits 

165 core.getlimits._register_known_types() 

166 

167 __all__.extend(['__version__', 'show_config']) 

168 __all__.extend(core.__all__) 

169 __all__.extend(_mat.__all__) 

170 __all__.extend(lib.__all__) 

171 __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma']) 

172 

173 # These are added by `from .core import *` and `core.__all__`, but we 

174 # overwrite them above with builtins we do _not_ want to export. 

175 __all__.remove('long') 

176 __all__.remove('unicode') 

177 

178 # Remove things that are in the numpy.lib but not in the numpy namespace 

179 # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace) 

180 # that prevents adding more things to the main namespace by accident. 

181 # The list below will grow until the `from .lib import *` fixme above is 

182 # taken care of 

183 __all__.remove('Arrayterator') 

184 del Arrayterator 

185 

186 # Filter out Cython harmless warnings 

187 warnings.filterwarnings("ignore", message="numpy.dtype size changed") 

188 warnings.filterwarnings("ignore", message="numpy.ufunc size changed") 

189 warnings.filterwarnings("ignore", message="numpy.ndarray size changed") 

190 

191 # oldnumeric and numarray were removed in 1.9. In case some packages import 

192 # but do not use them, we define them here for backward compatibility. 

193 oldnumeric = 'removed' 

194 numarray = 'removed' 

195 

196 if sys.version_info[:2] >= (3, 7): 

197 # Importing Tester requires importing all of UnitTest which is not a 

198 # cheap import Since it is mainly used in test suits, we lazy import it 

199 # here to save on the order of 10 ms of import time for most users 

200 # 

201 # The previous way Tester was imported also had a side effect of adding 

202 # the full `numpy.testing` namespace 

203 # 

204 # module level getattr is only supported in 3.7 onwards 

205 # https://www.python.org/dev/peps/pep-0562/ 

206 def __getattr__(attr): 

207 if attr == 'testing': 

208 import numpy.testing as testing 

209 return testing 

210 elif attr == 'Tester': 

211 from .testing import Tester 

212 return Tester 

213 else: 

214 raise AttributeError("module {!r} has no attribute " 

215 "{!r}".format(__name__, attr)) 

216 

217 def __dir__(): 

218 return list(globals().keys() | {'Tester', 'testing'}) 

219 

220 else: 

221 # We don't actually use this ourselves anymore, but I'm not 100% sure that 

222 # no-one else in the world is using it (though I hope not) 

223 from .testing import Tester 

224 

225 # Pytest testing 

226 from numpy._pytesttester import PytestTester 

227 test = PytestTester(__name__) 

228 del PytestTester 

229 

230 

231 def _sanity_check(): 

232 """ 

233 Quick sanity checks for common bugs caused by environment. 

234 There are some cases e.g. with wrong BLAS ABI that cause wrong 

235 results under specific runtime conditions that are not necessarily 

236 achieved during test suite runs, and it is useful to catch those early. 

237 

238 See https://github.com/numpy/numpy/issues/8577 and other 

239 similar bug reports. 

240 

241 """ 

242 try: 

243 x = ones(2, dtype=float32) 

244 if not abs(x.dot(x) - 2.0) < 1e-5: 

245 raise AssertionError() 

246 except AssertionError: 

247 msg = ("The current Numpy installation ({!r}) fails to " 

248 "pass simple sanity checks. This can be caused for example " 

249 "by incorrect BLAS library being linked in, or by mixing " 

250 "package managers (pip, conda, apt, ...). Search closed " 

251 "numpy issues for similar problems.") 

252 raise RuntimeError(msg.format(__file__)) 

253 

254 _sanity_check() 

255 del _sanity_check 

256 

257 def _mac_os_check(): 

258 """ 

259 Quick Sanity check for Mac OS look for accelerate build bugs. 

260 Testing numpy polyfit calls init_dgelsd(LAPACK) 

261 """ 

262 try: 

263 c = array([3., 2., 1.]) 

264 x = linspace(0, 2, 5) 

265 y = polyval(c, x) 

266 _ = polyfit(x, y, 2, cov=True) 

267 except ValueError: 

268 pass 

269 

270 import sys 

271 if sys.platform == "darwin": 

272 with warnings.catch_warnings(record=True) as w: 

273 _mac_os_check() 

274 # Throw runtime error, if the test failed Check for warning and error_message 

275 error_message = "" 

276 if len(w) > 0: 

277 error_message = "{}: {}".format(w[-1].category.__name__, str(w[-1].message)) 

278 msg = ( 

279 "Polyfit sanity test emitted a warning, most likely due " 

280 "to using a buggy Accelerate backend. " 

281 "If you compiled yourself, " 

282 "see site.cfg.example for information. " 

283 "Otherwise report this to the vendor " 

284 "that provided NumPy.\n{}\n".format( 

285 error_message)) 

286 raise RuntimeError(msg) 

287 del _mac_os_check 

288 

289 # We usually use madvise hugepages support, but on some old kernels it 

290 # is slow and thus better avoided. 

291 # Specifically kernel version 4.6 had a bug fix which probably fixed this: 

292 # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff 

293 import os 

294 use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None) 

295 if sys.platform == "linux" and use_hugepage is None: 

296 use_hugepage = 1 

297 kernel_version = os.uname().release.split(".")[:2] 

298 kernel_version = tuple(int(v) for v in kernel_version) 

299 if kernel_version < (4, 6): 

300 use_hugepage = 0 

301 elif use_hugepage is None: 

302 # This is not Linux, so it should not matter, just enable anyway 

303 use_hugepage = 1 

304 else: 

305 use_hugepage = int(use_hugepage) 

306 

307 # Note that this will currently only make a difference on Linux 

308 core.multiarray._set_madvise_hugepage(use_hugepage)