Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/__init__.py: 70%

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

159 statements  

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://numpy.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--------------------- 

55lib 

56 Basic functions used by several sub-packages. 

57random 

58 Core Random Tools 

59linalg 

60 Core Linear Algebra Tools 

61fft 

62 Core FFT routines 

63polynomial 

64 Polynomial tools 

65testing 

66 NumPy testing tools 

67distutils 

68 Enhancements to distutils with support for 

69 Fortran compilers support and more (for Python <= 3.11). 

70 

71Utilities 

72--------- 

73test 

74 Run numpy unittests 

75show_config 

76 Show numpy build configuration 

77matlib 

78 Make everything matrices. 

79__version__ 

80 NumPy version string 

81 

82Viewing documentation using IPython 

83----------------------------------- 

84 

85Start IPython and import `numpy` usually under the alias ``np``: `import 

86numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste 

87examples into the shell. To see which functions are available in `numpy`, 

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

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

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

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

92the source code). 

93 

94Copies vs. in-place operation 

95----------------------------- 

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

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

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

99Exceptions to this rule are documented. 

100 

101""" 

102import sys 

103import warnings 

104 

105from ._globals import _NoValue, _CopyMode 

106# These exceptions were moved in 1.25 and are hidden from __dir__() 

107from .exceptions import ( 

108 ComplexWarning, ModuleDeprecationWarning, VisibleDeprecationWarning, 

109 TooHardError, AxisError) 

110 

111 

112# If a version with git hash was stored, use that instead 

113from . import version 

114from .version import __version__ 

115 

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

117# procedure itself in a reliable manner. 

118try: 

119 __NUMPY_SETUP__ 

120except NameError: 

121 __NUMPY_SETUP__ = False 

122 

123if __NUMPY_SETUP__: 

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

125else: 

126 # Allow distributors to run custom init code before importing numpy.core 

127 from . import _distributor_init 

128 

129 try: 

130 from numpy.__config__ import show as show_config 

131 except ImportError as e: 

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

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

134 your python interpreter from there.""" 

135 raise ImportError(msg) from e 

136 

137 __all__ = [ 

138 'exceptions', 'ModuleDeprecationWarning', 'VisibleDeprecationWarning', 

139 'ComplexWarning', 'TooHardError', 'AxisError'] 

140 

141 # mapping of {name: (value, deprecation_msg)} 

142 __deprecated_attrs__ = {} 

143 

144 from . import core 

145 from .core import * 

146 from . import compat 

147 from . import exceptions 

148 from . import dtypes 

149 from . import lib 

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

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

152 from .lib import * 

153 

154 from . import linalg 

155 from . import fft 

156 from . import polynomial 

157 from . import random 

158 from . import ctypeslib 

159 from . import ma 

160 from . import matrixlib as _mat 

161 from .matrixlib import * 

162 

163 # Deprecations introduced in NumPy 1.20.0, 2020-06-06 

164 import builtins as _builtins 

165 

166 _msg = ( 

167 "module 'numpy' has no attribute '{n}'.\n" 

168 "`np.{n}` was a deprecated alias for the builtin `{n}`. " 

169 "To avoid this error in existing code, use `{n}` by itself. " 

170 "Doing this will not modify any behavior and is safe. {extended_msg}\n" 

171 "The aliases was originally deprecated in NumPy 1.20; for more " 

172 "details and guidance see the original release note at:\n" 

173 " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations") 

174 

175 _specific_msg = ( 

176 "If you specifically wanted the numpy scalar type, use `np.{}` here.") 

177 

178 _int_extended_msg = ( 

179 "When replacing `np.{}`, you may wish to use e.g. `np.int64` " 

180 "or `np.int32` to specify the precision. If you wish to review " 

181 "your current use, check the release note link for " 

182 "additional information.") 

183 

184 _type_info = [ 

185 ("object", ""), # The NumPy scalar only exists by name. 

186 ("bool", _specific_msg.format("bool_")), 

187 ("float", _specific_msg.format("float64")), 

188 ("complex", _specific_msg.format("complex128")), 

189 ("str", _specific_msg.format("str_")), 

190 ("int", _int_extended_msg.format("int"))] 

191 

192 __former_attrs__ = { 

193 n: _msg.format(n=n, extended_msg=extended_msg) 

194 for n, extended_msg in _type_info 

195 } 

196 

197 # Future warning introduced in NumPy 1.24.0, 2022-11-17 

198 _msg = ( 

199 "`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)") 

200 

201 # Some of these are awkward (since `np.str` may be preferable in the long 

202 # term), but overall the names ending in 0 seem undesirable 

203 _type_info = [ 

204 ("bool8", bool_, "np.bool_"), 

205 ("int0", intp, "np.intp"), 

206 ("uint0", uintp, "np.uintp"), 

207 ("str0", str_, "np.str_"), 

208 ("bytes0", bytes_, "np.bytes_"), 

209 ("void0", void, "np.void"), 

210 ("object0", object_, 

211 "`np.object0` is a deprecated alias for `np.object_`. " 

212 "`object` can be used instead. (Deprecated NumPy 1.24)")] 

213 

214 # Some of these could be defined right away, but most were aliases to 

215 # the Python objects and only removed in NumPy 1.24. Defining them should 

216 # probably wait for NumPy 1.26 or 2.0. 

217 # When defined, these should possibly not be added to `__all__` to avoid 

218 # import with `from numpy import *`. 

219 __future_scalars__ = {"bool", "long", "ulong", "str", "bytes", "object"} 

220 

221 __deprecated_attrs__.update({ 

222 n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info}) 

223 

224 import math 

225 

226 __deprecated_attrs__['math'] = (math, 

227 "`np.math` is a deprecated alias for the standard library `math` " 

228 "module (Deprecated Numpy 1.25). Replace usages of `np.math` with " 

229 "`math`") 

230 

231 del math, _msg, _type_info 

232 

233 from .core import abs 

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

235 core.getlimits._register_known_types() 

236 

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

238 __all__.extend(core.__all__) 

239 __all__.extend(_mat.__all__) 

240 __all__.extend(lib.__all__) 

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

242 

243 # Remove min and max from __all__ to avoid `from numpy import *` override 

244 # the builtins min/max. Temporary fix for 1.25.x/1.26.x, see gh-24229. 

245 __all__.remove('min') 

246 __all__.remove('max') 

247 __all__.remove('round') 

248 

249 # Remove one of the two occurrences of `issubdtype`, which is exposed as 

250 # both `numpy.core.issubdtype` and `numpy.lib.issubdtype`. 

251 __all__.remove('issubdtype') 

252 

253 # These are exported by np.core, but are replaced by the builtins below 

254 # remove them to ensure that we don't end up with `np.long == np.int_`, 

255 # which would be a breaking change. 

256 del long, unicode 

257 __all__.remove('long') 

258 __all__.remove('unicode') 

259 

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

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

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

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

264 # taken care of 

265 __all__.remove('Arrayterator') 

266 del Arrayterator 

267 

268 # These names were removed in NumPy 1.20. For at least one release, 

269 # attempts to access these names in the numpy namespace will trigger 

270 # a warning, and calling the function will raise an exception. 

271 _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt', 

272 'ppmt', 'pv', 'rate'] 

273 __expired_functions__ = { 

274 name: (f'In accordance with NEP 32, the function {name} was removed ' 

275 'from NumPy version 1.20. A replacement for this function ' 

276 'is available in the numpy_financial library: ' 

277 'https://pypi.org/project/numpy-financial') 

278 for name in _financial_names} 

279 

280 # Filter out Cython harmless warnings 

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

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

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

284 

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

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

287 oldnumeric = 'removed' 

288 numarray = 'removed' 

289 

290 def __getattr__(attr): 

291 # Warn for expired attributes, and return a dummy function 

292 # that always raises an exception. 

293 import warnings 

294 import math 

295 try: 

296 msg = __expired_functions__[attr] 

297 except KeyError: 

298 pass 

299 else: 

300 warnings.warn(msg, DeprecationWarning, stacklevel=2) 

301 

302 def _expired(*args, **kwds): 

303 raise RuntimeError(msg) 

304 

305 return _expired 

306 

307 # Emit warnings for deprecated attributes 

308 try: 

309 val, msg = __deprecated_attrs__[attr] 

310 except KeyError: 

311 pass 

312 else: 

313 warnings.warn(msg, DeprecationWarning, stacklevel=2) 

314 return val 

315 

316 if attr in __future_scalars__: 

317 # And future warnings for those that will change, but also give 

318 # the AttributeError 

319 warnings.warn( 

320 f"In the future `np.{attr}` will be defined as the " 

321 "corresponding NumPy scalar.", FutureWarning, stacklevel=2) 

322 

323 if attr in __former_attrs__: 

324 raise AttributeError(__former_attrs__[attr]) 

325 

326 if attr == 'testing': 

327 import numpy.testing as testing 

328 return testing 

329 elif attr == 'Tester': 

330 "Removed in NumPy 1.25.0" 

331 raise RuntimeError("Tester was removed in NumPy 1.25.") 

332 

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

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

335 

336 def __dir__(): 

337 public_symbols = globals().keys() | {'testing'} 

338 public_symbols -= { 

339 "core", "matrixlib", 

340 # These were moved in 1.25 and may be deprecated eventually: 

341 "ModuleDeprecationWarning", "VisibleDeprecationWarning", 

342 "ComplexWarning", "TooHardError", "AxisError" 

343 } 

344 return list(public_symbols) 

345 

346 # Pytest testing 

347 from numpy._pytesttester import PytestTester 

348 test = PytestTester(__name__) 

349 del PytestTester 

350 

351 def _sanity_check(): 

352 """ 

353 Quick sanity checks for common bugs caused by environment. 

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

355 results under specific runtime conditions that are not necessarily 

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

357 

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

359 similar bug reports. 

360 

361 """ 

362 try: 

363 x = ones(2, dtype=float32) 

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

365 raise AssertionError() 

366 except AssertionError: 

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

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

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

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

371 "numpy issues for similar problems.") 

372 raise RuntimeError(msg.format(__file__)) from None 

373 

374 _sanity_check() 

375 del _sanity_check 

376 

377 def _mac_os_check(): 

378 """ 

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

380 Testing numpy polyfit calls init_dgelsd(LAPACK) 

381 """ 

382 try: 

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

384 x = linspace(0, 2, 5) 

385 y = polyval(c, x) 

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

387 except ValueError: 

388 pass 

389 

390 if sys.platform == "darwin": 

391 from . import exceptions 

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

393 _mac_os_check() 

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

395 if len(w) > 0: 

396 for _wn in w: 

397 if _wn.category is exceptions.RankWarning: 

398 # Ignore other warnings, they may not be relevant (see gh-25433). 

399 error_message = f"{_wn.category.__name__}: {str(_wn.message)}" 

400 msg = ( 

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

402 "to using a buggy Accelerate backend." 

403 "\nIf you compiled yourself, more information is available at:" 

404 "\nhttps://numpy.org/devdocs/building/index.html" 

405 "\nOtherwise report this to the vendor " 

406 "that provided NumPy.\n\n{}\n".format(error_message)) 

407 raise RuntimeError(msg) 

408 del _wn 

409 del w 

410 del _mac_os_check 

411 

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

413 # is slow and thus better avoided. 

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

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

416 import os 

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

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

419 # If there is an issue with parsing the kernel version, 

420 # set use_hugepages to 0. Usage of LooseVersion will handle 

421 # the kernel version parsing better, but avoided since it 

422 # will increase the import time. See: #16679 for related discussion. 

423 try: 

424 use_hugepage = 1 

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

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

427 if kernel_version < (4, 6): 

428 use_hugepage = 0 

429 except ValueError: 

430 use_hugepages = 0 

431 elif use_hugepage is None: 

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

433 use_hugepage = 1 

434 else: 

435 use_hugepage = int(use_hugepage) 

436 

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

438 core.multiarray._set_madvise_hugepage(use_hugepage) 

439 del use_hugepage 

440 

441 # Give a warning if NumPy is reloaded or imported on a sub-interpreter 

442 # We do this from python, since the C-module may not be reloaded and 

443 # it is tidier organized. 

444 core.multiarray._multiarray_umath._reload_guard() 

445 

446 # default to "weak" promotion for "NumPy 2". 

447 core._set_promotion_state( 

448 os.environ.get("NPY_PROMOTION_STATE", 

449 "weak" if _using_numpy2_behavior() else "legacy")) 

450 

451 # Tell PyInstaller where to find hook-numpy.py 

452 def _pyinstaller_hooks_dir(): 

453 from pathlib import Path 

454 return [str(Path(__file__).with_name("_pyinstaller").resolve())] 

455 

456 # Remove symbols imported for internal use 

457 del os 

458 

459 

460# Remove symbols imported for internal use 

461del sys, warnings