Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/numpy/__init__.py: 57%

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

189 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 

41Available subpackages 

42--------------------- 

43lib 

44 Basic functions used by several sub-packages. 

45random 

46 Core Random Tools 

47linalg 

48 Core Linear Algebra Tools 

49fft 

50 Core FFT routines 

51polynomial 

52 Polynomial tools 

53testing 

54 NumPy testing tools 

55distutils 

56 Enhancements to distutils with support for 

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

58 

59Utilities 

60--------- 

61test 

62 Run numpy unittests 

63show_config 

64 Show numpy build configuration 

65__version__ 

66 NumPy version string 

67 

68Viewing documentation using IPython 

69----------------------------------- 

70 

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

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

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

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

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

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

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

78the source code). 

79 

80Copies vs. in-place operation 

81----------------------------- 

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

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

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

85Exceptions to this rule are documented. 

86 

87""" 

88import os 

89import sys 

90import warnings 

91 

92from ._globals import _NoValue, _CopyMode 

93from ._expired_attrs_2_0 import __expired_attributes__ 

94 

95 

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

97from . import version 

98from .version import __version__ 

99 

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

101# procedure itself in a reliable manner. 

102try: 

103 __NUMPY_SETUP__ 

104except NameError: 

105 __NUMPY_SETUP__ = False 

106 

107if __NUMPY_SETUP__: 

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

109else: 

110 # Allow distributors to run custom init code before importing numpy._core 

111 from . import _distributor_init 

112 

113 try: 

114 from numpy.__config__ import show_config 

115 except ImportError as e: 

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

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

118 your python interpreter from there.""" 

119 raise ImportError(msg) from e 

120 

121 from . import _core 

122 from ._core import ( 

123 False_, ScalarType, True_, 

124 abs, absolute, acos, acosh, add, all, allclose, 

125 amax, amin, any, arange, arccos, arccosh, arcsin, arcsinh, 

126 arctan, arctan2, arctanh, argmax, argmin, argpartition, argsort, 

127 argwhere, around, array, array2string, array_equal, array_equiv, 

128 array_repr, array_str, asanyarray, asarray, ascontiguousarray, 

129 asfortranarray, asin, asinh, atan, atanh, atan2, astype, atleast_1d, 

130 atleast_2d, atleast_3d, base_repr, binary_repr, bitwise_and, 

131 bitwise_count, bitwise_invert, bitwise_left_shift, bitwise_not, 

132 bitwise_or, bitwise_right_shift, bitwise_xor, block, bool, bool_, 

133 broadcast, busday_count, busday_offset, busdaycalendar, byte, bytes_, 

134 can_cast, cbrt, cdouble, ceil, character, choose, clip, clongdouble, 

135 complex128, complex64, complexfloating, compress, concat, concatenate, 

136 conj, conjugate, convolve, copysign, copyto, correlate, cos, cosh, 

137 count_nonzero, cross, csingle, cumprod, cumsum, cumulative_prod, 

138 cumulative_sum, datetime64, datetime_as_string, datetime_data, 

139 deg2rad, degrees, diagonal, divide, divmod, dot, double, dtype, e, 

140 einsum, einsum_path, empty, empty_like, equal, errstate, euler_gamma, 

141 exp, exp2, expm1, fabs, finfo, flatiter, flatnonzero, flexible, 

142 float16, float32, float64, float_power, floating, floor, floor_divide, 

143 fmax, fmin, fmod, format_float_positional, format_float_scientific, 

144 frexp, from_dlpack, frombuffer, fromfile, fromfunction, fromiter, 

145 frompyfunc, fromstring, full, full_like, gcd, generic, geomspace, 

146 get_printoptions, getbufsize, geterr, geterrcall, greater, 

147 greater_equal, half, heaviside, hstack, hypot, identity, iinfo, 

148 indices, inexact, inf, inner, int16, int32, int64, int8, int_, intc, 

149 integer, intp, invert, is_busday, isclose, isdtype, isfinite, 

150 isfortran, isinf, isnan, isnat, isscalar, issubdtype, lcm, ldexp, 

151 left_shift, less, less_equal, lexsort, linspace, little_endian, log, 

152 log10, log1p, log2, logaddexp, logaddexp2, logical_and, logical_not, 

153 logical_or, logical_xor, logspace, long, longdouble, longlong, matmul, 

154 matvec, matrix_transpose, max, maximum, may_share_memory, mean, memmap, 

155 min, min_scalar_type, minimum, mod, modf, moveaxis, multiply, nan, 

156 ndarray, ndim, nditer, negative, nested_iters, newaxis, nextafter, 

157 nonzero, not_equal, number, object_, ones, ones_like, outer, partition, 

158 permute_dims, pi, positive, pow, power, printoptions, prod, 

159 promote_types, ptp, put, putmask, rad2deg, radians, ravel, recarray, 

160 reciprocal, record, remainder, repeat, require, reshape, resize, 

161 result_type, right_shift, rint, roll, rollaxis, round, sctypeDict, 

162 searchsorted, set_printoptions, setbufsize, seterr, seterrcall, shape, 

163 shares_memory, short, sign, signbit, signedinteger, sin, single, sinh, 

164 size, sort, spacing, sqrt, square, squeeze, stack, std, 

165 str_, subtract, sum, swapaxes, take, tan, tanh, tensordot, 

166 timedelta64, trace, transpose, true_divide, trunc, typecodes, ubyte, 

167 ufunc, uint, uint16, uint32, uint64, uint8, uintc, uintp, ulong, 

168 ulonglong, unsignedinteger, unstack, ushort, var, vdot, vecdot, 

169 vecmat, void, vstack, where, zeros, zeros_like 

170 ) 

171 

172 # NOTE: It's still under discussion whether these aliases 

173 # should be removed. 

174 for ta in ["float96", "float128", "complex192", "complex256"]: 

175 try: 

176 globals()[ta] = getattr(_core, ta) 

177 except AttributeError: 

178 pass 

179 del ta 

180 

181 from . import lib 

182 from .lib import scimath as emath 

183 from .lib._histograms_impl import ( 

184 histogram, histogram_bin_edges, histogramdd 

185 ) 

186 from .lib._nanfunctions_impl import ( 

187 nanargmax, nanargmin, nancumprod, nancumsum, nanmax, nanmean, 

188 nanmedian, nanmin, nanpercentile, nanprod, nanquantile, nanstd, 

189 nansum, nanvar 

190 ) 

191 from .lib._function_base_impl import ( 

192 select, piecewise, trim_zeros, copy, iterable, percentile, diff, 

193 gradient, angle, unwrap, sort_complex, flip, rot90, extract, place, 

194 vectorize, asarray_chkfinite, average, bincount, digitize, cov, 

195 corrcoef, median, sinc, hamming, hanning, bartlett, blackman, 

196 kaiser, trapezoid, trapz, i0, meshgrid, delete, insert, append, 

197 interp, quantile 

198 ) 

199 from .lib._twodim_base_impl import ( 

200 diag, diagflat, eye, fliplr, flipud, tri, triu, tril, vander, 

201 histogram2d, mask_indices, tril_indices, tril_indices_from, 

202 triu_indices, triu_indices_from 

203 ) 

204 from .lib._shape_base_impl import ( 

205 apply_over_axes, apply_along_axis, array_split, column_stack, dsplit, 

206 dstack, expand_dims, hsplit, kron, put_along_axis, row_stack, split, 

207 take_along_axis, tile, vsplit 

208 ) 

209 from .lib._type_check_impl import ( 

210 iscomplexobj, isrealobj, imag, iscomplex, isreal, nan_to_num, real, 

211 real_if_close, typename, mintypecode, common_type 

212 ) 

213 from .lib._arraysetops_impl import ( 

214 ediff1d, in1d, intersect1d, isin, setdiff1d, setxor1d, union1d, 

215 unique, unique_all, unique_counts, unique_inverse, unique_values 

216 ) 

217 from .lib._ufunclike_impl import fix, isneginf, isposinf 

218 from .lib._arraypad_impl import pad 

219 from .lib._utils_impl import ( 

220 show_runtime, get_include, info 

221 ) 

222 from .lib._stride_tricks_impl import ( 

223 broadcast_arrays, broadcast_shapes, broadcast_to 

224 ) 

225 from .lib._polynomial_impl import ( 

226 poly, polyint, polyder, polyadd, polysub, polymul, polydiv, polyval, 

227 polyfit, poly1d, roots 

228 ) 

229 from .lib._npyio_impl import ( 

230 savetxt, loadtxt, genfromtxt, load, save, savez, packbits, 

231 savez_compressed, unpackbits, fromregex 

232 ) 

233 from .lib._index_tricks_impl import ( 

234 diag_indices_from, diag_indices, fill_diagonal, ndindex, ndenumerate, 

235 ix_, c_, r_, s_, ogrid, mgrid, unravel_index, ravel_multi_index, 

236 index_exp 

237 ) 

238 

239 from . import matrixlib as _mat 

240 from .matrixlib import ( 

241 asmatrix, bmat, matrix 

242 ) 

243 

244 # public submodules are imported lazily, therefore are accessible from 

245 # __getattr__. Note that `distutils` (deprecated) and `array_api` 

246 # (experimental label) are not added here, because `from numpy import *` 

247 # must not raise any warnings - that's too disruptive. 

248 __numpy_submodules__ = { 

249 "linalg", "fft", "dtypes", "random", "polynomial", "ma", 

250 "exceptions", "lib", "ctypeslib", "testing", "typing", 

251 "f2py", "test", "rec", "char", "core", "strings", 

252 } 

253 

254 # We build warning messages for former attributes 

255 _msg = ( 

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

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

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

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

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

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

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

263 

264 _specific_msg = ( 

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

266 

267 _int_extended_msg = ( 

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

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

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

271 "additional information.") 

272 

273 _type_info = [ 

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

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

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

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

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

279 

280 __former_attrs__ = { 

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

282 for n, extended_msg in _type_info 

283 } 

284 

285 

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

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

288 # probably wait for NumPy 1.26 or 2.0. 

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

290 # import with `from numpy import *`. 

291 __future_scalars__ = {"str", "bytes", "object"} 

292 

293 __array_api_version__ = "2023.12" 

294 

295 from ._array_api_info import __array_namespace_info__ 

296 

297 # now that numpy core module is imported, can initialize limits 

298 _core.getlimits._register_known_types() 

299 

300 __all__ = list( 

301 __numpy_submodules__ | 

302 set(_core.__all__) | 

303 set(_mat.__all__) | 

304 set(lib._histograms_impl.__all__) | 

305 set(lib._nanfunctions_impl.__all__) | 

306 set(lib._function_base_impl.__all__) | 

307 set(lib._twodim_base_impl.__all__) | 

308 set(lib._shape_base_impl.__all__) | 

309 set(lib._type_check_impl.__all__) | 

310 set(lib._arraysetops_impl.__all__) | 

311 set(lib._ufunclike_impl.__all__) | 

312 set(lib._arraypad_impl.__all__) | 

313 set(lib._utils_impl.__all__) | 

314 set(lib._stride_tricks_impl.__all__) | 

315 set(lib._polynomial_impl.__all__) | 

316 set(lib._npyio_impl.__all__) | 

317 set(lib._index_tricks_impl.__all__) | 

318 {"emath", "show_config", "__version__", "__array_namespace_info__"} 

319 ) 

320 

321 # Filter out Cython harmless warnings 

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

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

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

325 

326 def __getattr__(attr): 

327 # Warn for expired attributes 

328 import warnings 

329 

330 if attr == "linalg": 

331 import numpy.linalg as linalg 

332 return linalg 

333 elif attr == "fft": 

334 import numpy.fft as fft 

335 return fft 

336 elif attr == "dtypes": 

337 import numpy.dtypes as dtypes 

338 return dtypes 

339 elif attr == "random": 

340 import numpy.random as random 

341 return random 

342 elif attr == "polynomial": 

343 import numpy.polynomial as polynomial 

344 return polynomial 

345 elif attr == "ma": 

346 import numpy.ma as ma 

347 return ma 

348 elif attr == "ctypeslib": 

349 import numpy.ctypeslib as ctypeslib 

350 return ctypeslib 

351 elif attr == "exceptions": 

352 import numpy.exceptions as exceptions 

353 return exceptions 

354 elif attr == "testing": 

355 import numpy.testing as testing 

356 return testing 

357 elif attr == "matlib": 

358 import numpy.matlib as matlib 

359 return matlib 

360 elif attr == "f2py": 

361 import numpy.f2py as f2py 

362 return f2py 

363 elif attr == "typing": 

364 import numpy.typing as typing 

365 return typing 

366 elif attr == "rec": 

367 import numpy.rec as rec 

368 return rec 

369 elif attr == "char": 

370 import numpy.char as char 

371 return char 

372 elif attr == "array_api": 

373 raise AttributeError("`numpy.array_api` is not available from " 

374 "numpy 2.0 onwards", name=None) 

375 elif attr == "core": 

376 import numpy.core as core 

377 return core 

378 elif attr == "strings": 

379 import numpy.strings as strings 

380 return strings 

381 elif attr == "distutils": 

382 if 'distutils' in __numpy_submodules__: 

383 import numpy.distutils as distutils 

384 return distutils 

385 else: 

386 raise AttributeError("`numpy.distutils` is not available from " 

387 "Python 3.12 onwards", name=None) 

388 

389 if attr in __future_scalars__: 

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

391 # the AttributeError 

392 warnings.warn( 

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

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

395 

396 if attr in __former_attrs__: 

397 raise AttributeError(__former_attrs__[attr], name=None) 

398 

399 if attr in __expired_attributes__: 

400 raise AttributeError( 

401 f"`np.{attr}` was removed in the NumPy 2.0 release. " 

402 f"{__expired_attributes__[attr]}", 

403 name=None 

404 ) 

405 

406 if attr == "chararray": 

407 warnings.warn( 

408 "`np.chararray` is deprecated and will be removed from " 

409 "the main namespace in the future. Use an array with a string " 

410 "or bytes dtype instead.", DeprecationWarning, stacklevel=2) 

411 import numpy.char as char 

412 return char.chararray 

413 

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

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

416 

417 def __dir__(): 

418 public_symbols = ( 

419 globals().keys() | __numpy_submodules__ 

420 ) 

421 public_symbols -= { 

422 "matrixlib", "matlib", "tests", "conftest", "version", 

423 "compat", "distutils", "array_api" 

424 } 

425 return list(public_symbols) 

426 

427 # Pytest testing 

428 from numpy._pytesttester import PytestTester 

429 test = PytestTester(__name__) 

430 del PytestTester 

431 

432 def _sanity_check(): 

433 """ 

434 Quick sanity checks for common bugs caused by environment. 

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

436 results under specific runtime conditions that are not necessarily 

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

438 

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

440 similar bug reports. 

441 

442 """ 

443 try: 

444 x = ones(2, dtype=float32) 

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

446 raise AssertionError 

447 except AssertionError: 

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

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

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

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

452 "numpy issues for similar problems.") 

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

454 

455 _sanity_check() 

456 del _sanity_check 

457 

458 def _mac_os_check(): 

459 """ 

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

461 Testing numpy polyfit calls init_dgelsd(LAPACK) 

462 """ 

463 try: 

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

465 x = linspace(0, 2, 5) 

466 y = polyval(c, x) 

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

468 except ValueError: 

469 pass 

470 

471 if sys.platform == "darwin": 

472 from . import exceptions 

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

474 _mac_os_check() 

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

476 if len(w) > 0: 

477 for _wn in w: 

478 if _wn.category is exceptions.RankWarning: 

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

480 error_message = ( 

481 f"{_wn.category.__name__}: {_wn.message}" 

482 ) 

483 msg = ( 

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

485 "to using a buggy Accelerate backend." 

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

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

488 "\nOtherwise report this to the vendor " 

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

490 raise RuntimeError(msg) 

491 del _wn 

492 del w 

493 del _mac_os_check 

494 

495 def hugepage_setup(): 

496 """ 

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

498 is slow and thus better avoided. Specifically kernel version 4.6 

499 had a bug fix which probably fixed this: 

500 https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff 

501 """ 

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

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

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

505 # set use_hugepage to 0. Usage of LooseVersion will handle 

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

507 # will increase the import time. 

508 # See: #16679 for related discussion. 

509 try: 

510 use_hugepage = 1 

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

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

513 if kernel_version < (4, 6): 

514 use_hugepage = 0 

515 except ValueError: 

516 use_hugepage = 0 

517 elif use_hugepage is None: 

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

519 use_hugepage = 1 

520 else: 

521 use_hugepage = int(use_hugepage) 

522 return use_hugepage 

523 

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

525 _core.multiarray._set_madvise_hugepage(hugepage_setup()) 

526 del hugepage_setup 

527 

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

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

530 # it is tidier organized. 

531 _core.multiarray._multiarray_umath._reload_guard() 

532 

533 # TODO: Remove the environment variable entirely now that it is "weak" 

534 if (os.environ.get("NPY_PROMOTION_STATE", "weak") != "weak"): 

535 warnings.warn( 

536 "NPY_PROMOTION_STATE was a temporary feature for NumPy 2.0 " 

537 "transition and is ignored after NumPy 2.2.", 

538 UserWarning, stacklevel=2) 

539 

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

541 def _pyinstaller_hooks_dir(): 

542 from pathlib import Path 

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

544 

545 

546# Remove symbols imported for internal use 

547del os, sys, warnings