1"""

2 NumPy

3=====

4

5 Provides

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

10 How to use the documentation

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

12 Documentation is available in two forms: docstrings provided

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

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

15

16 We recommend exploring the docstrings using

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

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

19 instructions.

20

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

22

23 >>> import numpy as np

24

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

26

27 >>> x = 42

28 >>> x = x + 1

29

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

31

32 >>> help(np.sort)

33 ... # doctest: +SKIP

34

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

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

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

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

39 np.info() function does.

40

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

42

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

44 ... # doctest: +SKIP

45

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

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

48

49 >>> from numpy import doc

50 >>> help(doc)

51 ... # doctest: +SKIP

52

53 Available subpackages

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

55 lib

56 Basic functions used by several sub-packages.

57 random

58 Core Random Tools

59 linalg

60 Core Linear Algebra Tools

61 fft

62 Core FFT routines

63 polynomial

64 Polynomial tools

65 testing

66 NumPy testing tools

67 distutils

68 Enhancements to distutils with support for

69 Fortran compilers support and more.

70

71 Utilities

72---------

73 test

74 Run numpy unittests

75 show_config

76 Show numpy build configuration

77 dual

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`.

81 matlib

82 Make everything matrices.

83__version__

84 NumPy version string

85

86 Viewing documentation using IPython

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

88

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

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

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

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

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

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

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

96 the source code).

97

98 Copies vs. in-place operation

99-----------------------------

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

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

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

103 Exceptions to this rule are documented.

104

105"""

106 import sys

107 import warnings

108

109 from ._globals import (

110 ModuleDeprecationWarning, VisibleDeprecationWarning,

111 _NoValue, _CopyMode

112)

113

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

115# procedure itself in a reliable manner.

116 try:

117 __NUMPY_SETUP__

118 except NameError:

119 __NUMPY_SETUP__ = False

120

121 if __NUMPY_SETUP__:

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

123 else:

124 try:

125 from numpy.__config__ import show as show_config

126 except ImportError as e:

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

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

129 your python interpreter from there."""

130 raise ImportError(msg) from e

131

132 __all__ = ['ModuleDeprecationWarning',

133 'VisibleDeprecationWarning']

134

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

136 __deprecated_attrs__ = {}

137

138 # Allow distributors to run custom init code

139 from . import _distributor_init

140

141 from . import core

142 from .core import *

143 from . import compat

144 from . import lib

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

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

147 from .lib import *

148

149 from . import linalg

150 from . import fft

151 from . import polynomial

152 from . import random

153 from . import ctypeslib

154 from . import ma

155 from . import matrixlib as _mat

156 from .matrixlib import *

157

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

159 import builtins as _builtins

160

161 _msg = (

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

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

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

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

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

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

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

169

170 _specific_msg = (

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

172

173 _int_extended_msg = (

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

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

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

177 "additional information.")

178

179 _type_info = [

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

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

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

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

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

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

186

187 __former_attrs__ = {

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

189 for n, extended_msg in _type_info

190 }

191

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

193 _msg = (

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

195

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

197 # term), but overall the names ending in 0 seem undesireable

198 _type_info = [

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

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

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

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

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

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

205 ("object0", object_,

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

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

208

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

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

211 # probably wait for NumPy 1.26 or 2.0.

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

213 # import with `from numpy import *`.

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

215

216 __deprecated_attrs__.update({

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

218

219 del _msg, _type_info

220

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

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

223 core.getlimits._register_known_types()

224

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

226 __all__.extend(core.__all__)

227 __all__.extend(_mat.__all__)

228 __all__.extend(lib.__all__)

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

230

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

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

233 __all__.remove('issubdtype')

234

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

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

237 # which would be a breaking change.

238 del long, unicode

239 __all__.remove('long')

240 __all__.remove('unicode')

241

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

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

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

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

246 # taken care of

247 __all__.remove('Arrayterator')

248 del Arrayterator

249

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

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

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

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

254 'ppmt', 'pv', 'rate']

255 __expired_functions__ = {

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

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

258 'is available in the numpy_financial library: '

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

260 for name in _financial_names}

261

262 # Filter out Cython harmless warnings

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

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

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

266

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

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

269 oldnumeric = 'removed'

270 numarray = 'removed'

271

272 def __getattr__(attr):

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

274 # that always raises an exception.

275 import warnings

276 try:

277 msg = __expired_functions__[attr]

278 except KeyError:

279 pass

280 else:

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

282

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

284 raise RuntimeError(msg)

285

286 return _expired

287

288 # Emit warnings for deprecated attributes

289 try:

290 val, msg = __deprecated_attrs__[attr]

291 except KeyError:

292 pass

293 else:

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

295 return val

296

297 if attr in __future_scalars__:

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

299 # the AttributeError

300 warnings.warn(

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

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

303

304 if attr in __former_attrs__:

305 raise AttributeError(__former_attrs__[attr])

306

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

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

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

310 #

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

312 # the full `numpy.testing` namespace

313 if attr == 'testing':

314 import numpy.testing as testing

315 return testing

316 elif attr == 'Tester':

317 from .testing import Tester

318 return Tester

319

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

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

322

323 def __dir__():

324 public_symbols = globals().keys() | {'Tester', 'testing'}

325 public_symbols -= {

326 "core", "matrixlib",

327 }

328 return list(public_symbols)

329

330 # Pytest testing

331 from numpy._pytesttester import PytestTester

332 test = PytestTester(__name__)

333 del PytestTester

334

335 def _sanity_check():

336 """

337 Quick sanity checks for common bugs caused by environment.

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

339 results under specific runtime conditions that are not necessarily

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

341

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

343 similar bug reports.

344

345 """

346 try:

347 x = ones(2, dtype=float32)

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

349 raise AssertionError()

350 except AssertionError:

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

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

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

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

355 "numpy issues for similar problems.")

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

357

358 _sanity_check()

359 del _sanity_check

360

361 def _mac_os_check():

362 """

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

364 Testing numpy polyfit calls init_dgelsd(LAPACK)

365 """

366 try:

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

368 x = linspace(0, 2, 5)

369 y = polyval(c, x)

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

371 except ValueError:

372 pass

373

374 if sys.platform == "darwin":

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

376 _mac_os_check()

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

378 error_message = ""

379 if len(w) > 0:

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

381 msg = (

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

383 "to using a buggy Accelerate backend."

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

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

386 "\nOtherwise report this to the vendor "

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

388 raise RuntimeError(msg)

389 del _mac_os_check

390

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

392 # is slow and thus better avoided.

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

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

395 import os

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

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

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

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

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

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

402 try:

403 use_hugepage = 1

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

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

406 if kernel_version < (4, 6):

407 use_hugepage = 0

408 except ValueError:

409 use_hugepages = 0

410 elif use_hugepage is None:

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

412 use_hugepage = 1

413 else:

414 use_hugepage = int(use_hugepage)

415

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

417 core.multiarray._set_madvise_hugepage(use_hugepage)

418

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

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

421 # it is tidier organized.

422 core.multiarray._multiarray_umath._reload_guard()

423

424 core._set_promotion_state(os.environ.get("NPY_PROMOTION_STATE", "legacy"))

425

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

427 def _pyinstaller_hooks_dir():

428 from pathlib import Path

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

430

431 # Remove symbols imported for internal use

432 del os

433

434

435# get the version using versioneer

436 from .version import __version__, git_revision as __git_version__

437

438# Remove symbols imported for internal use

439 del sys, warnings