Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/numpy/__init__.py: 60%

137 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

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. 

70 

71Utilities 

72--------- 

73test 

74 Run numpy unittests 

75show_config 

76 Show numpy build configuration 

77dual 

78 Overwrite certain functions with high-performance SciPy tools. 

79 Note: `numpy.dual` is deprecated. Use the functions from NumPy or Scipy 

80 directly instead of importing them from `numpy.dual`. 

81matlib 

82 Make everything matrices. 

83__version__ 

84 NumPy version string 

85 

86Viewing documentation using IPython 

87----------------------------------- 

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

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

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

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

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

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

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

95the source code). 

96 

97Copies vs. in-place operation 

98----------------------------- 

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

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

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

102Exceptions to this rule are documented. 

103 

104""" 

105import sys 

106import warnings 

107 

108from ._globals import ( 

109 ModuleDeprecationWarning, VisibleDeprecationWarning, 

110 _NoValue, _CopyMode 

111) 

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__: 120 ↛ 121line 120 didn't jump to line 121, because the condition on line 120 was never true

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 as e: 

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) from e 

130 

131 __all__ = ['ModuleDeprecationWarning', 

132 'VisibleDeprecationWarning'] 

133 

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

135 __deprecated_attrs__ = {} 

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 # Deprecations introduced in NumPy 1.20.0, 2020-06-06 

158 import builtins as _builtins 

159 

160 _msg = ( 

161 "`np.{n}` is a deprecated alias for the builtin `{n}`. " 

162 "To silence this warning, use `{n}` by itself. Doing this will not " 

163 "modify any behavior and is safe. {extended_msg}\n" 

164 "Deprecated in NumPy 1.20; for more details and guidance: " 

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

166 

167 _specific_msg = ( 

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

169 

170 _int_extended_msg = ( 

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

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

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

174 "additional information.") 

175 

176 _type_info = [ 

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

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

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

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

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

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

183 

184 __deprecated_attrs__.update({ 

185 n: (getattr(_builtins, n), _msg.format(n=n, extended_msg=extended_msg)) 

186 for n, extended_msg in _type_info 

187 }) 

188 

189 # Numpy 1.20.0, 2020-10-19 

190 __deprecated_attrs__["typeDict"] = ( 

191 core.numerictypes.typeDict, 

192 "`np.typeDict` is a deprecated alias for `np.sctypeDict`." 

193 ) 

194 

195 # NumPy 1.22, 2021-10-20 

196 __deprecated_attrs__["MachAr"] = ( 

197 core._machar.MachAr, 

198 "`np.MachAr` is deprecated (NumPy 1.22)." 

199 ) 

200 

201 _msg = ( 

202 "`np.{n}` is a deprecated alias for `np.compat.{n}`. " 

203 "To silence this warning, use `np.compat.{n}` by itself. " 

204 "In the likely event your code does not need to work on Python 2 " 

205 "you can use the builtin `{n2}` for which `np.compat.{n}` is itself " 

206 "an alias. Doing this will not modify any behaviour and is safe. " 

207 "{extended_msg}\n" 

208 "Deprecated in NumPy 1.20; for more details and guidance: " 

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

210 

211 __deprecated_attrs__["long"] = ( 

212 getattr(compat, "long"), 

213 _msg.format(n="long", n2="int", 

214 extended_msg=_int_extended_msg.format("long"))) 

215 

216 __deprecated_attrs__["unicode"] = ( 

217 getattr(compat, "unicode"), 

218 _msg.format(n="unicode", n2="str", 

219 extended_msg=_specific_msg.format("str_"))) 

220 

221 del _msg, _specific_msg, _int_extended_msg, _type_info, _builtins 

222 

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

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

225 core.getlimits._register_known_types() 

226 

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

228 __all__.extend(core.__all__) 

229 __all__.extend(_mat.__all__) 

230 __all__.extend(lib.__all__) 

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

232 

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

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

235 __all__.remove('issubdtype') 

236 

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

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

239 # which would be a breaking change. 

240 del long, unicode 

241 __all__.remove('long') 

242 __all__.remove('unicode') 

243 

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

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

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

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

248 # taken care of 

249 __all__.remove('Arrayterator') 

250 del Arrayterator 

251 

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

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

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

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

256 'ppmt', 'pv', 'rate'] 

257 __expired_functions__ = { 

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

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

260 'is available in the numpy_financial library: ' 

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

262 for name in _financial_names} 

263 

264 # Filter out Cython harmless warnings 

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

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

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

268 

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

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

271 oldnumeric = 'removed' 

272 numarray = 'removed' 

273 

274 def __getattr__(attr): 

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

276 # that always raises an exception. 

277 try: 

278 msg = __expired_functions__[attr] 

279 except KeyError: 

280 pass 

281 else: 

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

283 

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

285 raise RuntimeError(msg) 

286 

287 return _expired 

288 

289 # Emit warnings for deprecated attributes 

290 try: 

291 val, msg = __deprecated_attrs__[attr] 

292 except KeyError: 

293 pass 

294 else: 

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

296 return val 

297 

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

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

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

301 # 

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

303 # the full `numpy.testing` namespace 

304 if attr == 'testing': 

305 import numpy.testing as testing 

306 return testing 

307 elif attr == 'Tester': 

308 from .testing import Tester 

309 return Tester 

310 

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

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

313 

314 def __dir__(): 

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

316 

317 # Pytest testing 

318 from numpy._pytesttester import PytestTester 

319 test = PytestTester(__name__) 

320 del PytestTester 

321 

322 def _sanity_check(): 

323 """ 

324 Quick sanity checks for common bugs caused by environment. 

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

326 results under specific runtime conditions that are not necessarily 

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

328 

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

330 similar bug reports. 

331 

332 """ 

333 try: 

334 x = ones(2, dtype=float32) 

335 if not abs(x.dot(x) - 2.0) < 1e-5: 335 ↛ 336line 335 didn't jump to line 336, because the condition on line 335 was never true

336 raise AssertionError() 

337 except AssertionError: 

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

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

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

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

342 "numpy issues for similar problems.") 

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

344 

345 _sanity_check() 

346 del _sanity_check 

347 

348 def _mac_os_check(): 

349 """ 

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

351 Testing numpy polyfit calls init_dgelsd(LAPACK) 

352 """ 

353 try: 

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

355 x = linspace(0, 2, 5) 

356 y = polyval(c, x) 

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

358 except ValueError: 

359 pass 

360 

361 import sys 

362 if sys.platform == "darwin": 362 ↛ 363line 362 didn't jump to line 363, because the condition on line 362 was never true

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

364 _mac_os_check() 

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

366 error_message = "" 

367 if len(w) > 0: 

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

369 msg = ( 

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

371 "to using a buggy Accelerate backend." 

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

373 "\nhttps://numpy.org/doc/stable/user/building.html#accelerated-blas-lapack-libraries" 

374 "\nOtherwise report this to the vendor " 

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

376 raise RuntimeError(msg) 

377 del _mac_os_check 

378 

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

380 # is slow and thus better avoided. 

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

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

383 import os 

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

385 if sys.platform == "linux" and use_hugepage is None: 385 ↛ 398line 385 didn't jump to line 398, because the condition on line 385 was never false

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

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

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

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

390 try: 

391 use_hugepage = 1 

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

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

394 if kernel_version < (4, 6): 394 ↛ 395line 394 didn't jump to line 395, because the condition on line 394 was never true

395 use_hugepage = 0 

396 except ValueError: 

397 use_hugepages = 0 

398 elif use_hugepage is None: 

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

400 use_hugepage = 1 

401 else: 

402 use_hugepage = int(use_hugepage) 

403 

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

405 core.multiarray._set_madvise_hugepage(use_hugepage) 

406 

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

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

409 # it is tidier organized. 

410 core.multiarray._multiarray_umath._reload_guard() 

411 

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

413 def _pyinstaller_hooks_dir(): 

414 from pathlib import Path 

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

416 

417 

418# get the version using versioneer 

419from .version import __version__, git_revision as __git_version__