Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/_core/numeric.py: 29%

495 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-09 06:12 +0000

1import functools 

2import itertools 

3import operator 

4import sys 

5import warnings 

6import numbers 

7import builtins 

8import math 

9 

10import numpy as np 

11from . import multiarray 

12from . import numerictypes as nt 

13from .multiarray import ( 

14 ALLOW_THREADS, BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, 

15 RAISE, WRAP, arange, array, asarray, asanyarray, ascontiguousarray, 

16 asfortranarray, broadcast, can_cast, concatenate, copyto, dot, dtype, 

17 empty, empty_like, flatiter, frombuffer, from_dlpack, fromfile, fromiter, 

18 fromstring, inner, lexsort, matmul, may_share_memory, min_scalar_type, 

19 ndarray, nditer, nested_iters, promote_types, putmask, result_type, 

20 shares_memory, vdot, where, zeros, normalize_axis_index, 

21 _get_promotion_state, _set_promotion_state 

22) 

23 

24from . import overrides 

25from . import umath 

26from . import shape_base 

27from .overrides import set_array_function_like_doc, set_module 

28from .umath import (multiply, invert, sin, PINF, NAN) 

29from . import numerictypes 

30from ..exceptions import AxisError 

31from ._ufunc_config import errstate, _no_nep50_warning 

32 

33bitwise_not = invert 

34ufunc = type(sin) 

35newaxis = None 

36 

37array_function_dispatch = functools.partial( 

38 overrides.array_function_dispatch, module='numpy') 

39 

40 

41__all__ = [ 

42 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', 

43 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray', 

44 'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype', 

45 'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where', 

46 'argwhere', 'copyto', 'concatenate', 'lexsort', 'astype', 

47 'can_cast', 'promote_types', 'min_scalar_type', 

48 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', 

49 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll', 

50 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 

51 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 

52 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones', 

53 'identity', 'allclose', 'putmask', 

54 'flatnonzero', 'inf', 'nan', 'False_', 'True_', 'bitwise_not', 

55 'full', 'full_like', 'matmul', 'shares_memory', 'may_share_memory', 

56 '_get_promotion_state', '_set_promotion_state'] 

57 

58 

59def _zeros_like_dispatcher( 

60 a, dtype=None, order=None, subok=None, shape=None, *, device=None 

61): 

62 return (a,) 

63 

64 

65@array_function_dispatch(_zeros_like_dispatcher) 

66def zeros_like( 

67 a, dtype=None, order='K', subok=True, shape=None, *, device=None 

68): 

69 """ 

70 Return an array of zeros with the same shape and type as a given array. 

71 

72 Parameters 

73 ---------- 

74 a : array_like 

75 The shape and data-type of `a` define these same attributes of 

76 the returned array. 

77 dtype : data-type, optional 

78 Overrides the data type of the result. 

79 

80 .. versionadded:: 1.6.0 

81 order : {'C', 'F', 'A', or 'K'}, optional 

82 Overrides the memory layout of the result. 'C' means C-order, 

83 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 

84 'C' otherwise. 'K' means match the layout of `a` as closely 

85 as possible. 

86 

87 .. versionadded:: 1.6.0 

88 subok : bool, optional. 

89 If True, then the newly created array will use the sub-class 

90 type of `a`, otherwise it will be a base-class array. Defaults 

91 to True. 

92 shape : int or sequence of ints, optional. 

93 Overrides the shape of the result. If order='K' and the number of 

94 dimensions is unchanged, will try to keep order, otherwise, 

95 order='C' is implied. 

96 

97 .. versionadded:: 1.17.0 

98 device : str, optional 

99 The device on which to place the created array. Default: None. 

100 For Array-API interoperability only, so must be ``"cpu"`` if passed. 

101 

102 .. versionadded:: 2.0.0 

103 

104 Returns 

105 ------- 

106 out : ndarray 

107 Array of zeros with the same shape and type as `a`. 

108 

109 See Also 

110 -------- 

111 empty_like : Return an empty array with shape and type of input. 

112 ones_like : Return an array of ones with shape and type of input. 

113 full_like : Return a new array with shape of input filled with value. 

114 zeros : Return a new array setting values to zero. 

115 

116 Examples 

117 -------- 

118 >>> x = np.arange(6) 

119 >>> x = x.reshape((2, 3)) 

120 >>> x 

121 array([[0, 1, 2], 

122 [3, 4, 5]]) 

123 >>> np.zeros_like(x) 

124 array([[0, 0, 0], 

125 [0, 0, 0]]) 

126 

127 >>> y = np.arange(3, dtype=float) 

128 >>> y 

129 array([0., 1., 2.]) 

130 >>> np.zeros_like(y) 

131 array([0., 0., 0.]) 

132 

133 """ 

134 res = empty_like( 

135 a, dtype=dtype, order=order, subok=subok, shape=shape, device=device 

136 ) 

137 # needed instead of a 0 to get same result as zeros for string dtypes 

138 z = zeros(1, dtype=res.dtype) 

139 multiarray.copyto(res, z, casting='unsafe') 

140 return res 

141 

142 

143@set_array_function_like_doc 

144@set_module('numpy') 

145def ones(shape, dtype=None, order='C', *, device=None, like=None): 

146 """ 

147 Return a new array of given shape and type, filled with ones. 

148 

149 Parameters 

150 ---------- 

151 shape : int or sequence of ints 

152 Shape of the new array, e.g., ``(2, 3)`` or ``2``. 

153 dtype : data-type, optional 

154 The desired data-type for the array, e.g., `numpy.int8`. Default is 

155 `numpy.float64`. 

156 order : {'C', 'F'}, optional, default: C 

157 Whether to store multi-dimensional data in row-major 

158 (C-style) or column-major (Fortran-style) order in 

159 memory. 

160 device : str, optional 

161 The device on which to place the created array. Default: None. 

162 For Array-API interoperability only, so must be ``"cpu"`` if passed. 

163 

164 .. versionadded:: 2.0.0 

165 ${ARRAY_FUNCTION_LIKE} 

166 

167 .. versionadded:: 1.20.0 

168 

169 Returns 

170 ------- 

171 out : ndarray 

172 Array of ones with the given shape, dtype, and order. 

173 

174 See Also 

175 -------- 

176 ones_like : Return an array of ones with shape and type of input. 

177 empty : Return a new uninitialized array. 

178 zeros : Return a new array setting values to zero. 

179 full : Return a new array of given shape filled with value. 

180 

181 Examples 

182 -------- 

183 >>> np.ones(5) 

184 array([1., 1., 1., 1., 1.]) 

185 

186 >>> np.ones((5,), dtype=int) 

187 array([1, 1, 1, 1, 1]) 

188 

189 >>> np.ones((2, 1)) 

190 array([[1.], 

191 [1.]]) 

192 

193 >>> s = (2,2) 

194 >>> np.ones(s) 

195 array([[1., 1.], 

196 [1., 1.]]) 

197 

198 """ 

199 if like is not None: 

200 return _ones_with_like( 

201 like, shape, dtype=dtype, order=order, device=device 

202 ) 

203 

204 a = empty(shape, dtype, order, device=device) 

205 multiarray.copyto(a, 1, casting='unsafe') 

206 return a 

207 

208 

209_ones_with_like = array_function_dispatch()(ones) 

210 

211 

212def _ones_like_dispatcher( 

213 a, dtype=None, order=None, subok=None, shape=None, *, device=None 

214): 

215 return (a,) 

216 

217 

218@array_function_dispatch(_ones_like_dispatcher) 

219def ones_like( 

220 a, dtype=None, order='K', subok=True, shape=None, *, device=None 

221): 

222 """ 

223 Return an array of ones with the same shape and type as a given array. 

224 

225 Parameters 

226 ---------- 

227 a : array_like 

228 The shape and data-type of `a` define these same attributes of 

229 the returned array. 

230 dtype : data-type, optional 

231 Overrides the data type of the result. 

232 

233 .. versionadded:: 1.6.0 

234 order : {'C', 'F', 'A', or 'K'}, optional 

235 Overrides the memory layout of the result. 'C' means C-order, 

236 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 

237 'C' otherwise. 'K' means match the layout of `a` as closely 

238 as possible. 

239 

240 .. versionadded:: 1.6.0 

241 subok : bool, optional. 

242 If True, then the newly created array will use the sub-class 

243 type of `a`, otherwise it will be a base-class array. Defaults 

244 to True. 

245 shape : int or sequence of ints, optional. 

246 Overrides the shape of the result. If order='K' and the number of 

247 dimensions is unchanged, will try to keep order, otherwise, 

248 order='C' is implied. 

249 

250 .. versionadded:: 1.17.0 

251 device : str, optional 

252 The device on which to place the created array. Default: None. 

253 For Array-API interoperability only, so must be ``"cpu"`` if passed. 

254 

255 .. versionadded:: 2.0.0 

256 

257 Returns 

258 ------- 

259 out : ndarray 

260 Array of ones with the same shape and type as `a`. 

261 

262 See Also 

263 -------- 

264 empty_like : Return an empty array with shape and type of input. 

265 zeros_like : Return an array of zeros with shape and type of input. 

266 full_like : Return a new array with shape of input filled with value. 

267 ones : Return a new array setting values to one. 

268 

269 Examples 

270 -------- 

271 >>> x = np.arange(6) 

272 >>> x = x.reshape((2, 3)) 

273 >>> x 

274 array([[0, 1, 2], 

275 [3, 4, 5]]) 

276 >>> np.ones_like(x) 

277 array([[1, 1, 1], 

278 [1, 1, 1]]) 

279 

280 >>> y = np.arange(3, dtype=float) 

281 >>> y 

282 array([0., 1., 2.]) 

283 >>> np.ones_like(y) 

284 array([1., 1., 1.]) 

285 

286 """ 

287 res = empty_like( 

288 a, dtype=dtype, order=order, subok=subok, shape=shape, device=device 

289 ) 

290 multiarray.copyto(res, 1, casting='unsafe') 

291 return res 

292 

293 

294def _full_dispatcher( 

295 shape, fill_value, dtype=None, order=None, *, device=None, like=None 

296): 

297 return(like,) 

298 

299 

300@set_array_function_like_doc 

301@set_module('numpy') 

302def full(shape, fill_value, dtype=None, order='C', *, device=None, like=None): 

303 """ 

304 Return a new array of given shape and type, filled with `fill_value`. 

305 

306 Parameters 

307 ---------- 

308 shape : int or sequence of ints 

309 Shape of the new array, e.g., ``(2, 3)`` or ``2``. 

310 fill_value : scalar or array_like 

311 Fill value. 

312 dtype : data-type, optional 

313 The desired data-type for the array The default, None, means 

314 ``np.array(fill_value).dtype``. 

315 order : {'C', 'F'}, optional 

316 Whether to store multidimensional data in C- or Fortran-contiguous 

317 (row- or column-wise) order in memory. 

318 device : str, optional 

319 The device on which to place the created array. Default: None. 

320 For Array-API interoperability only, so must be ``"cpu"`` if passed. 

321 

322 .. versionadded:: 2.0.0 

323 ${ARRAY_FUNCTION_LIKE} 

324 

325 .. versionadded:: 1.20.0 

326 

327 Returns 

328 ------- 

329 out : ndarray 

330 Array of `fill_value` with the given shape, dtype, and order. 

331 

332 See Also 

333 -------- 

334 full_like : Return a new array with shape of input filled with value. 

335 empty : Return a new uninitialized array. 

336 ones : Return a new array setting values to one. 

337 zeros : Return a new array setting values to zero. 

338 

339 Examples 

340 -------- 

341 >>> np.full((2, 2), np.inf) 

342 array([[inf, inf], 

343 [inf, inf]]) 

344 >>> np.full((2, 2), 10) 

345 array([[10, 10], 

346 [10, 10]]) 

347 

348 >>> np.full((2, 2), [1, 2]) 

349 array([[1, 2], 

350 [1, 2]]) 

351 

352 """ 

353 if like is not None: 

354 return _full_with_like( 

355 like, shape, fill_value, dtype=dtype, order=order, device=device 

356 ) 

357 

358 if dtype is None: 

359 fill_value = asarray(fill_value) 

360 dtype = fill_value.dtype 

361 a = empty(shape, dtype, order, device=device) 

362 multiarray.copyto(a, fill_value, casting='unsafe') 

363 return a 

364 

365 

366_full_with_like = array_function_dispatch()(full) 

367 

368 

369def _full_like_dispatcher( 

370 a, fill_value, dtype=None, order=None, subok=None, shape=None, 

371 *, device=None 

372): 

373 return (a,) 

374 

375 

376@array_function_dispatch(_full_like_dispatcher) 

377def full_like( 

378 a, fill_value, dtype=None, order='K', subok=True, shape=None, 

379 *, device=None 

380): 

381 """ 

382 Return a full array with the same shape and type as a given array. 

383 

384 Parameters 

385 ---------- 

386 a : array_like 

387 The shape and data-type of `a` define these same attributes of 

388 the returned array. 

389 fill_value : array_like 

390 Fill value. 

391 dtype : data-type, optional 

392 Overrides the data type of the result. 

393 order : {'C', 'F', 'A', or 'K'}, optional 

394 Overrides the memory layout of the result. 'C' means C-order, 

395 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 

396 'C' otherwise. 'K' means match the layout of `a` as closely 

397 as possible. 

398 subok : bool, optional. 

399 If True, then the newly created array will use the sub-class 

400 type of `a`, otherwise it will be a base-class array. Defaults 

401 to True. 

402 shape : int or sequence of ints, optional. 

403 Overrides the shape of the result. If order='K' and the number of 

404 dimensions is unchanged, will try to keep order, otherwise, 

405 order='C' is implied. 

406 

407 .. versionadded:: 1.17.0 

408 device : str, optional 

409 The device on which to place the created array. Default: None. 

410 For Array-API interoperability only, so must be ``"cpu"`` if passed. 

411 

412 .. versionadded:: 2.0.0 

413 

414 Returns 

415 ------- 

416 out : ndarray 

417 Array of `fill_value` with the same shape and type as `a`. 

418 

419 See Also 

420 -------- 

421 empty_like : Return an empty array with shape and type of input. 

422 ones_like : Return an array of ones with shape and type of input. 

423 zeros_like : Return an array of zeros with shape and type of input. 

424 full : Return a new array of given shape filled with value. 

425 

426 Examples 

427 -------- 

428 >>> x = np.arange(6, dtype=int) 

429 >>> np.full_like(x, 1) 

430 array([1, 1, 1, 1, 1, 1]) 

431 >>> np.full_like(x, 0.1) 

432 array([0, 0, 0, 0, 0, 0]) 

433 >>> np.full_like(x, 0.1, dtype=np.double) 

434 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) 

435 >>> np.full_like(x, np.nan, dtype=np.double) 

436 array([nan, nan, nan, nan, nan, nan]) 

437 

438 >>> y = np.arange(6, dtype=np.double) 

439 >>> np.full_like(y, 0.1) 

440 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) 

441 

442 >>> y = np.zeros([2, 2, 3], dtype=int) 

443 >>> np.full_like(y, [0, 0, 255]) 

444 array([[[ 0, 0, 255], 

445 [ 0, 0, 255]], 

446 [[ 0, 0, 255], 

447 [ 0, 0, 255]]]) 

448 """ 

449 res = empty_like( 

450 a, dtype=dtype, order=order, subok=subok, shape=shape, device=device 

451 ) 

452 multiarray.copyto(res, fill_value, casting='unsafe') 

453 return res 

454 

455 

456def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None): 

457 return (a,) 

458 

459 

460@array_function_dispatch(_count_nonzero_dispatcher) 

461def count_nonzero(a, axis=None, *, keepdims=False): 

462 """ 

463 Counts the number of non-zero values in the array ``a``. 

464 

465 The word "non-zero" is in reference to the Python 2.x 

466 built-in method ``__nonzero__()`` (renamed ``__bool__()`` 

467 in Python 3.x) of Python objects that tests an object's 

468 "truthfulness". For example, any number is considered 

469 truthful if it is nonzero, whereas any string is considered 

470 truthful if it is not the empty string. Thus, this function 

471 (recursively) counts how many elements in ``a`` (and in 

472 sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()`` 

473 method evaluated to ``True``. 

474 

475 Parameters 

476 ---------- 

477 a : array_like 

478 The array for which to count non-zeros. 

479 axis : int or tuple, optional 

480 Axis or tuple of axes along which to count non-zeros. 

481 Default is None, meaning that non-zeros will be counted 

482 along a flattened version of ``a``. 

483 

484 .. versionadded:: 1.12.0 

485 

486 keepdims : bool, optional 

487 If this is set to True, the axes that are counted are left 

488 in the result as dimensions with size one. With this option, 

489 the result will broadcast correctly against the input array. 

490 

491 .. versionadded:: 1.19.0 

492 

493 Returns 

494 ------- 

495 count : int or array of int 

496 Number of non-zero values in the array along a given axis. 

497 Otherwise, the total number of non-zero values in the array 

498 is returned. 

499 

500 See Also 

501 -------- 

502 nonzero : Return the coordinates of all the non-zero values. 

503 

504 Examples 

505 -------- 

506 >>> np.count_nonzero(np.eye(4)) 

507 4 

508 >>> a = np.array([[0, 1, 7, 0], 

509 ... [3, 0, 2, 19]]) 

510 >>> np.count_nonzero(a) 

511 5 

512 >>> np.count_nonzero(a, axis=0) 

513 array([1, 1, 2, 1]) 

514 >>> np.count_nonzero(a, axis=1) 

515 array([2, 3]) 

516 >>> np.count_nonzero(a, axis=1, keepdims=True) 

517 array([[2], 

518 [3]]) 

519 """ 

520 if axis is None and not keepdims: 

521 return multiarray.count_nonzero(a) 

522 

523 a = asanyarray(a) 

524 

525 # TODO: this works around .astype(bool) not working properly (gh-9847) 

526 if np.issubdtype(a.dtype, np.character): 

527 a_bool = a != a.dtype.type() 

528 else: 

529 a_bool = a.astype(np.bool, copy=False) 

530 

531 return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims) 

532 

533 

534@set_module('numpy') 

535def isfortran(a): 

536 """ 

537 Check if the array is Fortran contiguous but *not* C contiguous. 

538 

539 This function is obsolete. If you only want to check if an array is Fortran 

540 contiguous use ``a.flags.f_contiguous`` instead. 

541 

542 Parameters 

543 ---------- 

544 a : ndarray 

545 Input array. 

546 

547 Returns 

548 ------- 

549 isfortran : bool 

550 Returns True if the array is Fortran contiguous but *not* C contiguous. 

551 

552 

553 Examples 

554 -------- 

555 

556 np.array allows to specify whether the array is written in C-contiguous 

557 order (last index varies the fastest), or FORTRAN-contiguous order in 

558 memory (first index varies the fastest). 

559 

560 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') 

561 >>> a 

562 array([[1, 2, 3], 

563 [4, 5, 6]]) 

564 >>> np.isfortran(a) 

565 False 

566 

567 >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F') 

568 >>> b 

569 array([[1, 2, 3], 

570 [4, 5, 6]]) 

571 >>> np.isfortran(b) 

572 True 

573 

574 

575 The transpose of a C-ordered array is a FORTRAN-ordered array. 

576 

577 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') 

578 >>> a 

579 array([[1, 2, 3], 

580 [4, 5, 6]]) 

581 >>> np.isfortran(a) 

582 False 

583 >>> b = a.T 

584 >>> b 

585 array([[1, 4], 

586 [2, 5], 

587 [3, 6]]) 

588 >>> np.isfortran(b) 

589 True 

590 

591 C-ordered arrays evaluate as False even if they are also FORTRAN-ordered. 

592 

593 >>> np.isfortran(np.array([1, 2], order='F')) 

594 False 

595 

596 """ 

597 return a.flags.fnc 

598 

599 

600def _argwhere_dispatcher(a): 

601 return (a,) 

602 

603 

604@array_function_dispatch(_argwhere_dispatcher) 

605def argwhere(a): 

606 """ 

607 Find the indices of array elements that are non-zero, grouped by element. 

608 

609 Parameters 

610 ---------- 

611 a : array_like 

612 Input data. 

613 

614 Returns 

615 ------- 

616 index_array : (N, a.ndim) ndarray 

617 Indices of elements that are non-zero. Indices are grouped by element. 

618 This array will have shape ``(N, a.ndim)`` where ``N`` is the number of 

619 non-zero items. 

620 

621 See Also 

622 -------- 

623 where, nonzero 

624 

625 Notes 

626 ----- 

627 ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``, 

628 but produces a result of the correct shape for a 0D array. 

629 

630 The output of ``argwhere`` is not suitable for indexing arrays. 

631 For this purpose use ``nonzero(a)`` instead. 

632 

633 Examples 

634 -------- 

635 >>> x = np.arange(6).reshape(2,3) 

636 >>> x 

637 array([[0, 1, 2], 

638 [3, 4, 5]]) 

639 >>> np.argwhere(x>1) 

640 array([[0, 2], 

641 [1, 0], 

642 [1, 1], 

643 [1, 2]]) 

644 

645 """ 

646 # nonzero does not behave well on 0d, so promote to 1d 

647 if np.ndim(a) == 0: 

648 a = shape_base.atleast_1d(a) 

649 # then remove the added dimension 

650 return argwhere(a)[:, :0] 

651 return transpose(nonzero(a)) 

652 

653 

654def _flatnonzero_dispatcher(a): 

655 return (a,) 

656 

657 

658@array_function_dispatch(_flatnonzero_dispatcher) 

659def flatnonzero(a): 

660 """ 

661 Return indices that are non-zero in the flattened version of a. 

662 

663 This is equivalent to ``np.nonzero(np.ravel(a))[0]``. 

664 

665 Parameters 

666 ---------- 

667 a : array_like 

668 Input data. 

669 

670 Returns 

671 ------- 

672 res : ndarray 

673 Output array, containing the indices of the elements of ``a.ravel()`` 

674 that are non-zero. 

675 

676 See Also 

677 -------- 

678 nonzero : Return the indices of the non-zero elements of the input array. 

679 ravel : Return a 1-D array containing the elements of the input array. 

680 

681 Examples 

682 -------- 

683 >>> x = np.arange(-2, 3) 

684 >>> x 

685 array([-2, -1, 0, 1, 2]) 

686 >>> np.flatnonzero(x) 

687 array([0, 1, 3, 4]) 

688 

689 Use the indices of the non-zero elements as an index array to extract 

690 these elements: 

691 

692 >>> x.ravel()[np.flatnonzero(x)] 

693 array([-2, -1, 1, 2]) 

694 

695 """ 

696 return np.nonzero(np.ravel(a))[0] 

697 

698 

699def _correlate_dispatcher(a, v, mode=None): 

700 return (a, v) 

701 

702 

703@array_function_dispatch(_correlate_dispatcher) 

704def correlate(a, v, mode='valid'): 

705 r""" 

706 Cross-correlation of two 1-dimensional sequences. 

707 

708 This function computes the correlation as generally defined in signal 

709 processing texts [1]_: 

710 

711 .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v}_n 

712 

713 with a and v sequences being zero-padded where necessary and 

714 :math:`\overline v` denoting complex conjugation. 

715 

716 Parameters 

717 ---------- 

718 a, v : array_like 

719 Input sequences. 

720 mode : {'valid', 'same', 'full'}, optional 

721 Refer to the `convolve` docstring. Note that the default 

722 is 'valid', unlike `convolve`, which uses 'full'. 

723 

724 Returns 

725 ------- 

726 out : ndarray 

727 Discrete cross-correlation of `a` and `v`. 

728 

729 See Also 

730 -------- 

731 convolve : Discrete, linear convolution of two one-dimensional sequences. 

732 scipy.signal.correlate : uses FFT which has superior performance 

733 on large arrays. 

734 

735 Notes 

736 ----- 

737 The definition of correlation above is not unique and sometimes 

738 correlation may be defined differently. Another common definition is [1]_: 

739 

740 .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}} 

741 

742 which is related to :math:`c_k` by :math:`c'_k = c_{-k}`. 

743 

744 `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5) 

745 because it does not use the FFT to compute the convolution; in that case, 

746 `scipy.signal.correlate` might be preferable. 

747 

748 References 

749 ---------- 

750 .. [1] Wikipedia, "Cross-correlation", 

751 https://en.wikipedia.org/wiki/Cross-correlation 

752 

753 Examples 

754 -------- 

755 >>> np.correlate([1, 2, 3], [0, 1, 0.5]) 

756 array([3.5]) 

757 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same") 

758 array([2. , 3.5, 3. ]) 

759 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full") 

760 array([0.5, 2. , 3.5, 3. , 0. ]) 

761 

762 Using complex sequences: 

763 

764 >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full') 

765 array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ]) 

766 

767 Note that you get the time reversed, complex conjugated result 

768 (:math:`\overline{c_{-k}}`) when the two input sequences a and v change 

769 places: 

770 

771 >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full') 

772 array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j]) 

773 

774 """ 

775 return multiarray.correlate2(a, v, mode) 

776 

777 

778def _convolve_dispatcher(a, v, mode=None): 

779 return (a, v) 

780 

781 

782@array_function_dispatch(_convolve_dispatcher) 

783def convolve(a, v, mode='full'): 

784 """ 

785 Returns the discrete, linear convolution of two one-dimensional sequences. 

786 

787 The convolution operator is often seen in signal processing, where it 

788 models the effect of a linear time-invariant system on a signal [1]_. In 

789 probability theory, the sum of two independent random variables is 

790 distributed according to the convolution of their individual 

791 distributions. 

792 

793 If `v` is longer than `a`, the arrays are swapped before computation. 

794 

795 Parameters 

796 ---------- 

797 a : (N,) array_like 

798 First one-dimensional input array. 

799 v : (M,) array_like 

800 Second one-dimensional input array. 

801 mode : {'full', 'valid', 'same'}, optional 

802 'full': 

803 By default, mode is 'full'. This returns the convolution 

804 at each point of overlap, with an output shape of (N+M-1,). At 

805 the end-points of the convolution, the signals do not overlap 

806 completely, and boundary effects may be seen. 

807 

808 'same': 

809 Mode 'same' returns output of length ``max(M, N)``. Boundary 

810 effects are still visible. 

811 

812 'valid': 

813 Mode 'valid' returns output of length 

814 ``max(M, N) - min(M, N) + 1``. The convolution product is only given 

815 for points where the signals overlap completely. Values outside 

816 the signal boundary have no effect. 

817 

818 Returns 

819 ------- 

820 out : ndarray 

821 Discrete, linear convolution of `a` and `v`. 

822 

823 See Also 

824 -------- 

825 scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier 

826 Transform. 

827 scipy.linalg.toeplitz : Used to construct the convolution operator. 

828 polymul : Polynomial multiplication. Same output as convolve, but also 

829 accepts poly1d objects as input. 

830 

831 Notes 

832 ----- 

833 The discrete convolution operation is defined as 

834 

835 .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m} 

836 

837 It can be shown that a convolution :math:`x(t) * y(t)` in time/space 

838 is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier 

839 domain, after appropriate padding (padding is necessary to prevent 

840 circular convolution). Since multiplication is more efficient (faster) 

841 than convolution, the function `scipy.signal.fftconvolve` exploits the 

842 FFT to calculate the convolution of large data-sets. 

843 

844 References 

845 ---------- 

846 .. [1] Wikipedia, "Convolution", 

847 https://en.wikipedia.org/wiki/Convolution 

848 

849 Examples 

850 -------- 

851 Note how the convolution operator flips the second array 

852 before "sliding" the two across one another: 

853 

854 >>> np.convolve([1, 2, 3], [0, 1, 0.5]) 

855 array([0. , 1. , 2.5, 4. , 1.5]) 

856 

857 Only return the middle values of the convolution. 

858 Contains boundary effects, where zeros are taken 

859 into account: 

860 

861 >>> np.convolve([1,2,3],[0,1,0.5], 'same') 

862 array([1. , 2.5, 4. ]) 

863 

864 The two arrays are of the same length, so there 

865 is only one position where they completely overlap: 

866 

867 >>> np.convolve([1,2,3],[0,1,0.5], 'valid') 

868 array([2.5]) 

869 

870 """ 

871 a, v = array(a, copy=None, ndmin=1), array(v, copy=None, ndmin=1) 

872 if (len(v) > len(a)): 

873 a, v = v, a 

874 if len(a) == 0: 

875 raise ValueError('a cannot be empty') 

876 if len(v) == 0: 

877 raise ValueError('v cannot be empty') 

878 return multiarray.correlate(a, v[::-1], mode) 

879 

880 

881def _outer_dispatcher(a, b, out=None): 

882 return (a, b, out) 

883 

884 

885@array_function_dispatch(_outer_dispatcher) 

886def outer(a, b, out=None): 

887 """ 

888 Compute the outer product of two vectors. 

889 

890 Given two vectors `a` and `b` of length ``M`` and ``N``, respectively, 

891 the outer product [1]_ is:: 

892 

893 [[a_0*b_0 a_0*b_1 ... a_0*b_{N-1} ] 

894 [a_1*b_0 . 

895 [ ... . 

896 [a_{M-1}*b_0 a_{M-1}*b_{N-1} ]] 

897 

898 Parameters 

899 ---------- 

900 a : (M,) array_like 

901 First input vector. Input is flattened if 

902 not already 1-dimensional. 

903 b : (N,) array_like 

904 Second input vector. Input is flattened if 

905 not already 1-dimensional. 

906 out : (M, N) ndarray, optional 

907 A location where the result is stored 

908 

909 .. versionadded:: 1.9.0 

910 

911 Returns 

912 ------- 

913 out : (M, N) ndarray 

914 ``out[i, j] = a[i] * b[j]`` 

915 

916 See also 

917 -------- 

918 inner 

919 einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent. 

920 ufunc.outer : A generalization to dimensions other than 1D and other 

921 operations. ``np.multiply.outer(a.ravel(), b.ravel())`` 

922 is the equivalent. 

923 linalg.outer : An Array API compatible variation of ``np.outer``, 

924 which accepts 1-dimensional inputs only. 

925 tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))`` 

926 is the equivalent. 

927 

928 References 

929 ---------- 

930 .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd 

931 ed., Baltimore, MD, Johns Hopkins University Press, 1996, 

932 pg. 8. 

933 

934 Examples 

935 -------- 

936 Make a (*very* coarse) grid for computing a Mandelbrot set: 

937 

938 >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5)) 

939 >>> rl 

940 array([[-2., -1., 0., 1., 2.], 

941 [-2., -1., 0., 1., 2.], 

942 [-2., -1., 0., 1., 2.], 

943 [-2., -1., 0., 1., 2.], 

944 [-2., -1., 0., 1., 2.]]) 

945 >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,))) 

946 >>> im 

947 array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j], 

948 [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j], 

949 [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], 

950 [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j], 

951 [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) 

952 >>> grid = rl + im 

953 >>> grid 

954 array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j], 

955 [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j], 

956 [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j], 

957 [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j], 

958 [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]]) 

959 

960 An example using a "vector" of letters: 

961 

962 >>> x = np.array(['a', 'b', 'c'], dtype=object) 

963 >>> np.outer(x, [1, 2, 3]) 

964 array([['a', 'aa', 'aaa'], 

965 ['b', 'bb', 'bbb'], 

966 ['c', 'cc', 'ccc']], dtype=object) 

967 

968 """ 

969 a = asarray(a) 

970 b = asarray(b) 

971 return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out) 

972 

973 

974def _tensordot_dispatcher(a, b, axes=None): 

975 return (a, b) 

976 

977 

978@array_function_dispatch(_tensordot_dispatcher) 

979def tensordot(a, b, axes=2): 

980 """ 

981 Compute tensor dot product along specified axes. 

982 

983 Given two tensors, `a` and `b`, and an array_like object containing 

984 two array_like objects, ``(a_axes, b_axes)``, sum the products of 

985 `a`'s and `b`'s elements (components) over the axes specified by 

986 ``a_axes`` and ``b_axes``. The third argument can be a single non-negative 

987 integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions 

988 of `a` and the first ``N`` dimensions of `b` are summed over. 

989 

990 Parameters 

991 ---------- 

992 a, b : array_like 

993 Tensors to "dot". 

994 

995 axes : int or (2,) array_like 

996 * integer_like 

997 If an int N, sum over the last N axes of `a` and the first N axes 

998 of `b` in order. The sizes of the corresponding axes must match. 

999 * (2,) array_like 

1000 Or, a list of axes to be summed over, first sequence applying to `a`, 

1001 second to `b`. Both elements array_like must be of the same length. 

1002 

1003 Returns 

1004 ------- 

1005 output : ndarray 

1006 The tensor dot product of the input. 

1007 

1008 See Also 

1009 -------- 

1010 dot, einsum 

1011 

1012 Notes 

1013 ----- 

1014 Three common use cases are: 

1015 

1016 * ``axes = 0`` : tensor product :math:`a\\otimes b` 

1017 * ``axes = 1`` : tensor dot product :math:`a\\cdot b` 

1018 * ``axes = 2`` : (default) tensor double contraction :math:`a:b` 

1019 

1020 When `axes` is a positive integer ``N``, the operation starts with 

1021 axis ``-N`` of `a` and axis ``0`` of `b`, and it continues through 

1022 axis ``-1`` of `a` and axis ``N-1`` of `b` (inclusive). 

1023 

1024 When there is more than one axis to sum over - and they are not the last 

1025 (first) axes of `a` (`b`) - the argument `axes` should consist of 

1026 two sequences of the same length, with the first axis to sum over given 

1027 first in both sequences, the second axis second, and so forth. 

1028 

1029 The shape of the result consists of the non-contracted axes of the 

1030 first tensor, followed by the non-contracted axes of the second. 

1031 

1032 Examples 

1033 -------- 

1034 A "traditional" example: 

1035 

1036 >>> a = np.arange(60.).reshape(3,4,5) 

1037 >>> b = np.arange(24.).reshape(4,3,2) 

1038 >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) 

1039 >>> c.shape 

1040 (5, 2) 

1041 >>> c 

1042 array([[4400., 4730.], 

1043 [4532., 4874.], 

1044 [4664., 5018.], 

1045 [4796., 5162.], 

1046 [4928., 5306.]]) 

1047 >>> # A slower but equivalent way of computing the same... 

1048 >>> d = np.zeros((5,2)) 

1049 >>> for i in range(5): 

1050 ... for j in range(2): 

1051 ... for k in range(3): 

1052 ... for n in range(4): 

1053 ... d[i,j] += a[k,n,i] * b[n,k,j] 

1054 >>> c == d 

1055 array([[ True, True], 

1056 [ True, True], 

1057 [ True, True], 

1058 [ True, True], 

1059 [ True, True]]) 

1060 

1061 An extended example taking advantage of the overloading of + and \\*: 

1062 

1063 >>> a = np.array(range(1, 9)) 

1064 >>> a.shape = (2, 2, 2) 

1065 >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object) 

1066 >>> A.shape = (2, 2) 

1067 >>> a; A 

1068 array([[[1, 2], 

1069 [3, 4]], 

1070 [[5, 6], 

1071 [7, 8]]]) 

1072 array([['a', 'b'], 

1073 ['c', 'd']], dtype=object) 

1074 

1075 >>> np.tensordot(a, A) # third argument default is 2 for double-contraction 

1076 array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object) 

1077 

1078 >>> np.tensordot(a, A, 1) 

1079 array([[['acc', 'bdd'], 

1080 ['aaacccc', 'bbbdddd']], 

1081 [['aaaaacccccc', 'bbbbbdddddd'], 

1082 ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object) 

1083 

1084 >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.) 

1085 array([[[[['a', 'b'], 

1086 ['c', 'd']], 

1087 ... 

1088 

1089 >>> np.tensordot(a, A, (0, 1)) 

1090 array([[['abbbbb', 'cddddd'], 

1091 ['aabbbbbb', 'ccdddddd']], 

1092 [['aaabbbbbbb', 'cccddddddd'], 

1093 ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object) 

1094 

1095 >>> np.tensordot(a, A, (2, 1)) 

1096 array([[['abb', 'cdd'], 

1097 ['aaabbbb', 'cccdddd']], 

1098 [['aaaaabbbbbb', 'cccccdddddd'], 

1099 ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object) 

1100 

1101 >>> np.tensordot(a, A, ((0, 1), (0, 1))) 

1102 array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object) 

1103 

1104 >>> np.tensordot(a, A, ((2, 1), (1, 0))) 

1105 array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object) 

1106 

1107 """ 

1108 try: 

1109 iter(axes) 

1110 except Exception: 

1111 axes_a = list(range(-axes, 0)) 

1112 axes_b = list(range(0, axes)) 

1113 else: 

1114 axes_a, axes_b = axes 

1115 try: 

1116 na = len(axes_a) 

1117 axes_a = list(axes_a) 

1118 except TypeError: 

1119 axes_a = [axes_a] 

1120 na = 1 

1121 try: 

1122 nb = len(axes_b) 

1123 axes_b = list(axes_b) 

1124 except TypeError: 

1125 axes_b = [axes_b] 

1126 nb = 1 

1127 

1128 a, b = asarray(a), asarray(b) 

1129 as_ = a.shape 

1130 nda = a.ndim 

1131 bs = b.shape 

1132 ndb = b.ndim 

1133 equal = True 

1134 if na != nb: 

1135 equal = False 

1136 else: 

1137 for k in range(na): 

1138 if as_[axes_a[k]] != bs[axes_b[k]]: 

1139 equal = False 

1140 break 

1141 if axes_a[k] < 0: 

1142 axes_a[k] += nda 

1143 if axes_b[k] < 0: 

1144 axes_b[k] += ndb 

1145 if not equal: 

1146 raise ValueError("shape-mismatch for sum") 

1147 

1148 # Move the axes to sum over to the end of "a" 

1149 # and to the front of "b" 

1150 notin = [k for k in range(nda) if k not in axes_a] 

1151 newaxes_a = notin + axes_a 

1152 N2 = math.prod(as_[axis] for axis in axes_a) 

1153 newshape_a = (math.prod([as_[ax] for ax in notin]), N2) 

1154 olda = [as_[axis] for axis in notin] 

1155 

1156 notin = [k for k in range(ndb) if k not in axes_b] 

1157 newaxes_b = axes_b + notin 

1158 N2 = math.prod(bs[axis] for axis in axes_b) 

1159 newshape_b = (N2, math.prod([bs[ax] for ax in notin])) 

1160 oldb = [bs[axis] for axis in notin] 

1161 

1162 at = a.transpose(newaxes_a).reshape(newshape_a) 

1163 bt = b.transpose(newaxes_b).reshape(newshape_b) 

1164 res = dot(at, bt) 

1165 return res.reshape(olda + oldb) 

1166 

1167 

1168def _roll_dispatcher(a, shift, axis=None): 

1169 return (a,) 

1170 

1171 

1172@array_function_dispatch(_roll_dispatcher) 

1173def roll(a, shift, axis=None): 

1174 """ 

1175 Roll array elements along a given axis. 

1176 

1177 Elements that roll beyond the last position are re-introduced at 

1178 the first. 

1179 

1180 Parameters 

1181 ---------- 

1182 a : array_like 

1183 Input array. 

1184 shift : int or tuple of ints 

1185 The number of places by which elements are shifted. If a tuple, 

1186 then `axis` must be a tuple of the same size, and each of the 

1187 given axes is shifted by the corresponding number. If an int 

1188 while `axis` is a tuple of ints, then the same value is used for 

1189 all given axes. 

1190 axis : int or tuple of ints, optional 

1191 Axis or axes along which elements are shifted. By default, the 

1192 array is flattened before shifting, after which the original 

1193 shape is restored. 

1194 

1195 Returns 

1196 ------- 

1197 res : ndarray 

1198 Output array, with the same shape as `a`. 

1199 

1200 See Also 

1201 -------- 

1202 rollaxis : Roll the specified axis backwards, until it lies in a 

1203 given position. 

1204 

1205 Notes 

1206 ----- 

1207 .. versionadded:: 1.12.0 

1208 

1209 Supports rolling over multiple dimensions simultaneously. 

1210 

1211 Examples 

1212 -------- 

1213 >>> x = np.arange(10) 

1214 >>> np.roll(x, 2) 

1215 array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) 

1216 >>> np.roll(x, -2) 

1217 array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) 

1218 

1219 >>> x2 = np.reshape(x, (2, 5)) 

1220 >>> x2 

1221 array([[0, 1, 2, 3, 4], 

1222 [5, 6, 7, 8, 9]]) 

1223 >>> np.roll(x2, 1) 

1224 array([[9, 0, 1, 2, 3], 

1225 [4, 5, 6, 7, 8]]) 

1226 >>> np.roll(x2, -1) 

1227 array([[1, 2, 3, 4, 5], 

1228 [6, 7, 8, 9, 0]]) 

1229 >>> np.roll(x2, 1, axis=0) 

1230 array([[5, 6, 7, 8, 9], 

1231 [0, 1, 2, 3, 4]]) 

1232 >>> np.roll(x2, -1, axis=0) 

1233 array([[5, 6, 7, 8, 9], 

1234 [0, 1, 2, 3, 4]]) 

1235 >>> np.roll(x2, 1, axis=1) 

1236 array([[4, 0, 1, 2, 3], 

1237 [9, 5, 6, 7, 8]]) 

1238 >>> np.roll(x2, -1, axis=1) 

1239 array([[1, 2, 3, 4, 0], 

1240 [6, 7, 8, 9, 5]]) 

1241 >>> np.roll(x2, (1, 1), axis=(1, 0)) 

1242 array([[9, 5, 6, 7, 8], 

1243 [4, 0, 1, 2, 3]]) 

1244 >>> np.roll(x2, (2, 1), axis=(1, 0)) 

1245 array([[8, 9, 5, 6, 7], 

1246 [3, 4, 0, 1, 2]]) 

1247 

1248 """ 

1249 a = asanyarray(a) 

1250 if axis is None: 

1251 return roll(a.ravel(), shift, 0).reshape(a.shape) 

1252 

1253 else: 

1254 axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True) 

1255 broadcasted = broadcast(shift, axis) 

1256 if broadcasted.ndim > 1: 

1257 raise ValueError( 

1258 "'shift' and 'axis' should be scalars or 1D sequences") 

1259 shifts = {ax: 0 for ax in range(a.ndim)} 

1260 for sh, ax in broadcasted: 

1261 shifts[ax] += sh 

1262 

1263 rolls = [((slice(None), slice(None)),)] * a.ndim 

1264 for ax, offset in shifts.items(): 

1265 offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters. 

1266 if offset: 

1267 # (original, result), (original, result) 

1268 rolls[ax] = ((slice(None, -offset), slice(offset, None)), 

1269 (slice(-offset, None), slice(None, offset))) 

1270 

1271 result = empty_like(a) 

1272 for indices in itertools.product(*rolls): 

1273 arr_index, res_index = zip(*indices) 

1274 result[res_index] = a[arr_index] 

1275 

1276 return result 

1277 

1278 

1279def _rollaxis_dispatcher(a, axis, start=None): 

1280 return (a,) 

1281 

1282 

1283@array_function_dispatch(_rollaxis_dispatcher) 

1284def rollaxis(a, axis, start=0): 

1285 """ 

1286 Roll the specified axis backwards, until it lies in a given position. 

1287 

1288 This function continues to be supported for backward compatibility, but you 

1289 should prefer `moveaxis`. The `moveaxis` function was added in NumPy 

1290 1.11. 

1291 

1292 Parameters 

1293 ---------- 

1294 a : ndarray 

1295 Input array. 

1296 axis : int 

1297 The axis to be rolled. The positions of the other axes do not 

1298 change relative to one another. 

1299 start : int, optional 

1300 When ``start <= axis``, the axis is rolled back until it lies in 

1301 this position. When ``start > axis``, the axis is rolled until it 

1302 lies before this position. The default, 0, results in a "complete" 

1303 roll. The following table describes how negative values of ``start`` 

1304 are interpreted: 

1305 

1306 .. table:: 

1307 :align: left 

1308 

1309 +-------------------+----------------------+ 

1310 | ``start`` | Normalized ``start`` | 

1311 +===================+======================+ 

1312 | ``-(arr.ndim+1)`` | raise ``AxisError`` | 

1313 +-------------------+----------------------+ 

1314 | ``-arr.ndim`` | 0 | 

1315 +-------------------+----------------------+ 

1316 | |vdots| | |vdots| | 

1317 +-------------------+----------------------+ 

1318 | ``-1`` | ``arr.ndim-1`` | 

1319 +-------------------+----------------------+ 

1320 | ``0`` | ``0`` | 

1321 +-------------------+----------------------+ 

1322 | |vdots| | |vdots| | 

1323 +-------------------+----------------------+ 

1324 | ``arr.ndim`` | ``arr.ndim`` | 

1325 +-------------------+----------------------+ 

1326 | ``arr.ndim + 1`` | raise ``AxisError`` | 

1327 +-------------------+----------------------+ 

1328 

1329 .. |vdots| unicode:: U+22EE .. Vertical Ellipsis 

1330 

1331 Returns 

1332 ------- 

1333 res : ndarray 

1334 For NumPy >= 1.10.0 a view of `a` is always returned. For earlier 

1335 NumPy versions a view of `a` is returned only if the order of the 

1336 axes is changed, otherwise the input array is returned. 

1337 

1338 See Also 

1339 -------- 

1340 moveaxis : Move array axes to new positions. 

1341 roll : Roll the elements of an array by a number of positions along a 

1342 given axis. 

1343 

1344 Examples 

1345 -------- 

1346 >>> a = np.ones((3,4,5,6)) 

1347 >>> np.rollaxis(a, 3, 1).shape 

1348 (3, 6, 4, 5) 

1349 >>> np.rollaxis(a, 2).shape 

1350 (5, 3, 4, 6) 

1351 >>> np.rollaxis(a, 1, 4).shape 

1352 (3, 5, 6, 4) 

1353 

1354 """ 

1355 n = a.ndim 

1356 axis = normalize_axis_index(axis, n) 

1357 if start < 0: 

1358 start += n 

1359 msg = "'%s' arg requires %d <= %s < %d, but %d was passed in" 

1360 if not (0 <= start < n + 1): 

1361 raise AxisError(msg % ('start', -n, 'start', n + 1, start)) 

1362 if axis < start: 

1363 # it's been removed 

1364 start -= 1 

1365 if axis == start: 

1366 return a[...] 

1367 axes = list(range(0, n)) 

1368 axes.remove(axis) 

1369 axes.insert(start, axis) 

1370 return a.transpose(axes) 

1371 

1372 

1373@set_module("numpy.lib.array_utils") 

1374def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): 

1375 """ 

1376 Normalizes an axis argument into a tuple of non-negative integer axes. 

1377 

1378 This handles shorthands such as ``1`` and converts them to ``(1,)``, 

1379 as well as performing the handling of negative indices covered by 

1380 `normalize_axis_index`. 

1381 

1382 By default, this forbids axes from being specified multiple times. 

1383 

1384 Used internally by multi-axis-checking logic. 

1385 

1386 .. versionadded:: 1.13.0 

1387 

1388 Parameters 

1389 ---------- 

1390 axis : int, iterable of int 

1391 The un-normalized index or indices of the axis. 

1392 ndim : int 

1393 The number of dimensions of the array that `axis` should be normalized 

1394 against. 

1395 argname : str, optional 

1396 A prefix to put before the error message, typically the name of the 

1397 argument. 

1398 allow_duplicate : bool, optional 

1399 If False, the default, disallow an axis from being specified twice. 

1400 

1401 Returns 

1402 ------- 

1403 normalized_axes : tuple of int 

1404 The normalized axis index, such that `0 <= normalized_axis < ndim` 

1405 

1406 Raises 

1407 ------ 

1408 AxisError 

1409 If any axis provided is out of range 

1410 ValueError 

1411 If an axis is repeated 

1412 

1413 See also 

1414 -------- 

1415 normalize_axis_index : normalizing a single scalar axis 

1416 """ 

1417 # Optimization to speed-up the most common cases. 

1418 if type(axis) not in (tuple, list): 

1419 try: 

1420 axis = [operator.index(axis)] 

1421 except TypeError: 

1422 pass 

1423 # Going via an iterator directly is slower than via list comprehension. 

1424 axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis]) 

1425 if not allow_duplicate and len(set(axis)) != len(axis): 

1426 if argname: 

1427 raise ValueError('repeated axis in `{}` argument'.format(argname)) 

1428 else: 

1429 raise ValueError('repeated axis') 

1430 return axis 

1431 

1432 

1433def _moveaxis_dispatcher(a, source, destination): 

1434 return (a,) 

1435 

1436 

1437@array_function_dispatch(_moveaxis_dispatcher) 

1438def moveaxis(a, source, destination): 

1439 """ 

1440 Move axes of an array to new positions. 

1441 

1442 Other axes remain in their original order. 

1443 

1444 .. versionadded:: 1.11.0 

1445 

1446 Parameters 

1447 ---------- 

1448 a : np.ndarray 

1449 The array whose axes should be reordered. 

1450 source : int or sequence of int 

1451 Original positions of the axes to move. These must be unique. 

1452 destination : int or sequence of int 

1453 Destination positions for each of the original axes. These must also be 

1454 unique. 

1455 

1456 Returns 

1457 ------- 

1458 result : np.ndarray 

1459 Array with moved axes. This array is a view of the input array. 

1460 

1461 See Also 

1462 -------- 

1463 transpose : Permute the dimensions of an array. 

1464 swapaxes : Interchange two axes of an array. 

1465 

1466 Examples 

1467 -------- 

1468 >>> x = np.zeros((3, 4, 5)) 

1469 >>> np.moveaxis(x, 0, -1).shape 

1470 (4, 5, 3) 

1471 >>> np.moveaxis(x, -1, 0).shape 

1472 (5, 3, 4) 

1473 

1474 These all achieve the same result: 

1475 

1476 >>> np.transpose(x).shape 

1477 (5, 4, 3) 

1478 >>> np.swapaxes(x, 0, -1).shape 

1479 (5, 4, 3) 

1480 >>> np.moveaxis(x, [0, 1], [-1, -2]).shape 

1481 (5, 4, 3) 

1482 >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape 

1483 (5, 4, 3) 

1484 

1485 """ 

1486 try: 

1487 # allow duck-array types if they define transpose 

1488 transpose = a.transpose 

1489 except AttributeError: 

1490 a = asarray(a) 

1491 transpose = a.transpose 

1492 

1493 source = normalize_axis_tuple(source, a.ndim, 'source') 

1494 destination = normalize_axis_tuple(destination, a.ndim, 'destination') 

1495 if len(source) != len(destination): 

1496 raise ValueError('`source` and `destination` arguments must have ' 

1497 'the same number of elements') 

1498 

1499 order = [n for n in range(a.ndim) if n not in source] 

1500 

1501 for dest, src in sorted(zip(destination, source)): 

1502 order.insert(dest, src) 

1503 

1504 result = transpose(order) 

1505 return result 

1506 

1507 

1508def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None): 

1509 return (a, b) 

1510 

1511 

1512@array_function_dispatch(_cross_dispatcher) 

1513def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): 

1514 """ 

1515 Return the cross product of two (arrays of) vectors. 

1516 

1517 The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular 

1518 to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors 

1519 are defined by the last axis of `a` and `b` by default, and these axes 

1520 can have dimensions 2 or 3. Where the dimension of either `a` or `b` is 

1521 2, the third component of the input vector is assumed to be zero and the 

1522 cross product calculated accordingly. In cases where both input vectors 

1523 have dimension 2, the z-component of the cross product is returned. 

1524 

1525 Parameters 

1526 ---------- 

1527 a : array_like 

1528 Components of the first vector(s). 

1529 b : array_like 

1530 Components of the second vector(s). 

1531 axisa : int, optional 

1532 Axis of `a` that defines the vector(s). By default, the last axis. 

1533 axisb : int, optional 

1534 Axis of `b` that defines the vector(s). By default, the last axis. 

1535 axisc : int, optional 

1536 Axis of `c` containing the cross product vector(s). Ignored if 

1537 both input vectors have dimension 2, as the return is scalar. 

1538 By default, the last axis. 

1539 axis : int, optional 

1540 If defined, the axis of `a`, `b` and `c` that defines the vector(s) 

1541 and cross product(s). Overrides `axisa`, `axisb` and `axisc`. 

1542 

1543 Returns 

1544 ------- 

1545 c : ndarray 

1546 Vector cross product(s). 

1547 

1548 Raises 

1549 ------ 

1550 ValueError 

1551 When the dimension of the vector(s) in `a` and/or `b` does not 

1552 equal 2 or 3. 

1553 

1554 See Also 

1555 -------- 

1556 inner : Inner product 

1557 outer : Outer product. 

1558 linalg.cross : An Array API compatible variation of ``np.cross``, 

1559 which accepts (arrays of) 3-element vectors only. 

1560 ix_ : Construct index arrays. 

1561 

1562 Notes 

1563 ----- 

1564 .. versionadded:: 1.9.0 

1565 

1566 Supports full broadcasting of the inputs. 

1567 

1568 Examples 

1569 -------- 

1570 Vector cross-product. 

1571 

1572 >>> x = [1, 2, 3] 

1573 >>> y = [4, 5, 6] 

1574 >>> np.cross(x, y) 

1575 array([-3, 6, -3]) 

1576 

1577 One vector with dimension 2. 

1578 

1579 >>> x = [1, 2] 

1580 >>> y = [4, 5, 6] 

1581 >>> np.cross(x, y) 

1582 array([12, -6, -3]) 

1583 

1584 Equivalently: 

1585 

1586 >>> x = [1, 2, 0] 

1587 >>> y = [4, 5, 6] 

1588 >>> np.cross(x, y) 

1589 array([12, -6, -3]) 

1590 

1591 Both vectors with dimension 2. 

1592 

1593 >>> x = [1,2] 

1594 >>> y = [4,5] 

1595 >>> np.cross(x, y) 

1596 array(-3) 

1597 

1598 Multiple vector cross-products. Note that the direction of the cross 

1599 product vector is defined by the *right-hand rule*. 

1600 

1601 >>> x = np.array([[1,2,3], [4,5,6]]) 

1602 >>> y = np.array([[4,5,6], [1,2,3]]) 

1603 >>> np.cross(x, y) 

1604 array([[-3, 6, -3], 

1605 [ 3, -6, 3]]) 

1606 

1607 The orientation of `c` can be changed using the `axisc` keyword. 

1608 

1609 >>> np.cross(x, y, axisc=0) 

1610 array([[-3, 3], 

1611 [ 6, -6], 

1612 [-3, 3]]) 

1613 

1614 Change the vector definition of `x` and `y` using `axisa` and `axisb`. 

1615 

1616 >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]]) 

1617 >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]]) 

1618 >>> np.cross(x, y) 

1619 array([[ -6, 12, -6], 

1620 [ 0, 0, 0], 

1621 [ 6, -12, 6]]) 

1622 >>> np.cross(x, y, axisa=0, axisb=0) 

1623 array([[-24, 48, -24], 

1624 [-30, 60, -30], 

1625 [-36, 72, -36]]) 

1626 

1627 """ 

1628 if axis is not None: 

1629 axisa, axisb, axisc = (axis,) * 3 

1630 a = asarray(a) 

1631 b = asarray(b) 

1632 

1633 if (a.ndim < 1) or (b.ndim < 1): 

1634 raise ValueError("At least one array has zero dimension") 

1635 

1636 # Check axisa and axisb are within bounds 

1637 axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa') 

1638 axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb') 

1639 

1640 # Move working axis to the end of the shape 

1641 a = moveaxis(a, axisa, -1) 

1642 b = moveaxis(b, axisb, -1) 

1643 msg = ("incompatible dimensions for cross product\n" 

1644 "(dimension must be 2 or 3)") 

1645 if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3): 

1646 raise ValueError(msg) 

1647 if a.shape[-1] == 2 or b.shape[-1] == 2: 

1648 # Deprecated in NumPy 2.0, 2023-09-26 

1649 warnings.warn( 

1650 "Arrays of 2-dimensional vectors are deprecated. Use arrays of " 

1651 "3-dimensional vectors instead. (deprecated in NumPy 2.0)", 

1652 DeprecationWarning, stacklevel=2 

1653 ) 

1654 

1655 # Create the output array 

1656 shape = broadcast(a[..., 0], b[..., 0]).shape 

1657 if a.shape[-1] == 3 or b.shape[-1] == 3: 

1658 shape += (3,) 

1659 # Check axisc is within bounds 

1660 axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc') 

1661 dtype = promote_types(a.dtype, b.dtype) 

1662 cp = empty(shape, dtype) 

1663 

1664 # recast arrays as dtype 

1665 a = a.astype(dtype) 

1666 b = b.astype(dtype) 

1667 

1668 # create local aliases for readability 

1669 a0 = a[..., 0] 

1670 a1 = a[..., 1] 

1671 if a.shape[-1] == 3: 

1672 a2 = a[..., 2] 

1673 b0 = b[..., 0] 

1674 b1 = b[..., 1] 

1675 if b.shape[-1] == 3: 

1676 b2 = b[..., 2] 

1677 if cp.ndim != 0 and cp.shape[-1] == 3: 

1678 cp0 = cp[..., 0] 

1679 cp1 = cp[..., 1] 

1680 cp2 = cp[..., 2] 

1681 

1682 if a.shape[-1] == 2: 

1683 if b.shape[-1] == 2: 

1684 # a0 * b1 - a1 * b0 

1685 multiply(a0, b1, out=cp) 

1686 cp -= a1 * b0 

1687 return cp 

1688 else: 

1689 assert b.shape[-1] == 3 

1690 # cp0 = a1 * b2 - 0 (a2 = 0) 

1691 # cp1 = 0 - a0 * b2 (a2 = 0) 

1692 # cp2 = a0 * b1 - a1 * b0 

1693 multiply(a1, b2, out=cp0) 

1694 multiply(a0, b2, out=cp1) 

1695 negative(cp1, out=cp1) 

1696 multiply(a0, b1, out=cp2) 

1697 cp2 -= a1 * b0 

1698 else: 

1699 assert a.shape[-1] == 3 

1700 if b.shape[-1] == 3: 

1701 # cp0 = a1 * b2 - a2 * b1 

1702 # cp1 = a2 * b0 - a0 * b2 

1703 # cp2 = a0 * b1 - a1 * b0 

1704 multiply(a1, b2, out=cp0) 

1705 tmp = array(a2 * b1) 

1706 cp0 -= tmp 

1707 multiply(a2, b0, out=cp1) 

1708 multiply(a0, b2, out=tmp) 

1709 cp1 -= tmp 

1710 multiply(a0, b1, out=cp2) 

1711 multiply(a1, b0, out=tmp) 

1712 cp2 -= tmp 

1713 else: 

1714 assert b.shape[-1] == 2 

1715 # cp0 = 0 - a2 * b1 (b2 = 0) 

1716 # cp1 = a2 * b0 - 0 (b2 = 0) 

1717 # cp2 = a0 * b1 - a1 * b0 

1718 multiply(a2, b1, out=cp0) 

1719 negative(cp0, out=cp0) 

1720 multiply(a2, b0, out=cp1) 

1721 multiply(a0, b1, out=cp2) 

1722 cp2 -= a1 * b0 

1723 

1724 return moveaxis(cp, -1, axisc) 

1725 

1726 

1727little_endian = (sys.byteorder == 'little') 

1728 

1729 

1730@set_module('numpy') 

1731def indices(dimensions, dtype=int, sparse=False): 

1732 """ 

1733 Return an array representing the indices of a grid. 

1734 

1735 Compute an array where the subarrays contain index values 0, 1, ... 

1736 varying only along the corresponding axis. 

1737 

1738 Parameters 

1739 ---------- 

1740 dimensions : sequence of ints 

1741 The shape of the grid. 

1742 dtype : dtype, optional 

1743 Data type of the result. 

1744 sparse : boolean, optional 

1745 Return a sparse representation of the grid instead of a dense 

1746 representation. Default is False. 

1747 

1748 .. versionadded:: 1.17 

1749 

1750 Returns 

1751 ------- 

1752 grid : one ndarray or tuple of ndarrays 

1753 If sparse is False: 

1754 Returns one array of grid indices, 

1755 ``grid.shape = (len(dimensions),) + tuple(dimensions)``. 

1756 If sparse is True: 

1757 Returns a tuple of arrays, with 

1758 ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with 

1759 dimensions[i] in the ith place 

1760 

1761 See Also 

1762 -------- 

1763 mgrid, ogrid, meshgrid 

1764 

1765 Notes 

1766 ----- 

1767 The output shape in the dense case is obtained by prepending the number 

1768 of dimensions in front of the tuple of dimensions, i.e. if `dimensions` 

1769 is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is 

1770 ``(N, r0, ..., rN-1)``. 

1771 

1772 The subarrays ``grid[k]`` contains the N-D array of indices along the 

1773 ``k-th`` axis. Explicitly:: 

1774 

1775 grid[k, i0, i1, ..., iN-1] = ik 

1776 

1777 Examples 

1778 -------- 

1779 >>> grid = np.indices((2, 3)) 

1780 >>> grid.shape 

1781 (2, 2, 3) 

1782 >>> grid[0] # row indices 

1783 array([[0, 0, 0], 

1784 [1, 1, 1]]) 

1785 >>> grid[1] # column indices 

1786 array([[0, 1, 2], 

1787 [0, 1, 2]]) 

1788 

1789 The indices can be used as an index into an array. 

1790 

1791 >>> x = np.arange(20).reshape(5, 4) 

1792 >>> row, col = np.indices((2, 3)) 

1793 >>> x[row, col] 

1794 array([[0, 1, 2], 

1795 [4, 5, 6]]) 

1796 

1797 Note that it would be more straightforward in the above example to 

1798 extract the required elements directly with ``x[:2, :3]``. 

1799 

1800 If sparse is set to true, the grid will be returned in a sparse 

1801 representation. 

1802 

1803 >>> i, j = np.indices((2, 3), sparse=True) 

1804 >>> i.shape 

1805 (2, 1) 

1806 >>> j.shape 

1807 (1, 3) 

1808 >>> i # row indices 

1809 array([[0], 

1810 [1]]) 

1811 >>> j # column indices 

1812 array([[0, 1, 2]]) 

1813 

1814 """ 

1815 dimensions = tuple(dimensions) 

1816 N = len(dimensions) 

1817 shape = (1,)*N 

1818 if sparse: 

1819 res = tuple() 

1820 else: 

1821 res = empty((N,)+dimensions, dtype=dtype) 

1822 for i, dim in enumerate(dimensions): 

1823 idx = arange(dim, dtype=dtype).reshape( 

1824 shape[:i] + (dim,) + shape[i+1:] 

1825 ) 

1826 if sparse: 

1827 res = res + (idx,) 

1828 else: 

1829 res[i] = idx 

1830 return res 

1831 

1832 

1833@set_array_function_like_doc 

1834@set_module('numpy') 

1835def fromfunction(function, shape, *, dtype=float, like=None, **kwargs): 

1836 """ 

1837 Construct an array by executing a function over each coordinate. 

1838 

1839 The resulting array therefore has a value ``fn(x, y, z)`` at 

1840 coordinate ``(x, y, z)``. 

1841 

1842 Parameters 

1843 ---------- 

1844 function : callable 

1845 The function is called with N parameters, where N is the rank of 

1846 `shape`. Each parameter represents the coordinates of the array 

1847 varying along a specific axis. For example, if `shape` 

1848 were ``(2, 2)``, then the parameters would be 

1849 ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])`` 

1850 shape : (N,) tuple of ints 

1851 Shape of the output array, which also determines the shape of 

1852 the coordinate arrays passed to `function`. 

1853 dtype : data-type, optional 

1854 Data-type of the coordinate arrays passed to `function`. 

1855 By default, `dtype` is float. 

1856 ${ARRAY_FUNCTION_LIKE} 

1857 

1858 .. versionadded:: 1.20.0 

1859 

1860 Returns 

1861 ------- 

1862 fromfunction : any 

1863 The result of the call to `function` is passed back directly. 

1864 Therefore the shape of `fromfunction` is completely determined by 

1865 `function`. If `function` returns a scalar value, the shape of 

1866 `fromfunction` would not match the `shape` parameter. 

1867 

1868 See Also 

1869 -------- 

1870 indices, meshgrid 

1871 

1872 Notes 

1873 ----- 

1874 Keywords other than `dtype` and `like` are passed to `function`. 

1875 

1876 Examples 

1877 -------- 

1878 >>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float) 

1879 array([[0., 0.], 

1880 [1., 1.]]) 

1881 

1882 >>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float) 

1883 array([[0., 1.], 

1884 [0., 1.]]) 

1885 

1886 >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) 

1887 array([[ True, False, False], 

1888 [False, True, False], 

1889 [False, False, True]]) 

1890 

1891 >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) 

1892 array([[0, 1, 2], 

1893 [1, 2, 3], 

1894 [2, 3, 4]]) 

1895 

1896 """ 

1897 if like is not None: 

1898 return _fromfunction_with_like( 

1899 like, function, shape, dtype=dtype, **kwargs) 

1900 

1901 args = indices(shape, dtype=dtype) 

1902 return function(*args, **kwargs) 

1903 

1904 

1905_fromfunction_with_like = array_function_dispatch()(fromfunction) 

1906 

1907 

1908def _frombuffer(buf, dtype, shape, order): 

1909 return frombuffer(buf, dtype=dtype).reshape(shape, order=order) 

1910 

1911 

1912@set_module('numpy') 

1913def isscalar(element): 

1914 """ 

1915 Returns True if the type of `element` is a scalar type. 

1916 

1917 Parameters 

1918 ---------- 

1919 element : any 

1920 Input argument, can be of any type and shape. 

1921 

1922 Returns 

1923 ------- 

1924 val : bool 

1925 True if `element` is a scalar type, False if it is not. 

1926 

1927 See Also 

1928 -------- 

1929 ndim : Get the number of dimensions of an array 

1930 

1931 Notes 

1932 ----- 

1933 If you need a stricter way to identify a *numerical* scalar, use 

1934 ``isinstance(x, numbers.Number)``, as that returns ``False`` for most 

1935 non-numerical elements such as strings. 

1936 

1937 In most cases ``np.ndim(x) == 0`` should be used instead of this function, 

1938 as that will also return true for 0d arrays. This is how numpy overloads 

1939 functions in the style of the ``dx`` arguments to `gradient` and 

1940 the ``bins`` argument to `histogram`. Some key differences: 

1941 

1942 +------------------------------------+---------------+-------------------+ 

1943 | x |``isscalar(x)``|``np.ndim(x) == 0``| 

1944 +====================================+===============+===================+ 

1945 | PEP 3141 numeric objects | ``True`` | ``True`` | 

1946 | (including builtins) | | | 

1947 +------------------------------------+---------------+-------------------+ 

1948 | builtin string and buffer objects | ``True`` | ``True`` | 

1949 +------------------------------------+---------------+-------------------+ 

1950 | other builtin objects, like | ``False`` | ``True`` | 

1951 | `pathlib.Path`, `Exception`, | | | 

1952 | the result of `re.compile` | | | 

1953 +------------------------------------+---------------+-------------------+ 

1954 | third-party objects like | ``False`` | ``True`` | 

1955 | `matplotlib.figure.Figure` | | | 

1956 +------------------------------------+---------------+-------------------+ 

1957 | zero-dimensional numpy arrays | ``False`` | ``True`` | 

1958 +------------------------------------+---------------+-------------------+ 

1959 | other numpy arrays | ``False`` | ``False`` | 

1960 +------------------------------------+---------------+-------------------+ 

1961 | `list`, `tuple`, and other | ``False`` | ``False`` | 

1962 | sequence objects | | | 

1963 +------------------------------------+---------------+-------------------+ 

1964 

1965 Examples 

1966 -------- 

1967 >>> np.isscalar(3.1) 

1968 True 

1969 >>> np.isscalar(np.array(3.1)) 

1970 False 

1971 >>> np.isscalar([3.1]) 

1972 False 

1973 >>> np.isscalar(False) 

1974 True 

1975 >>> np.isscalar('numpy') 

1976 True 

1977 

1978 NumPy supports PEP 3141 numbers: 

1979 

1980 >>> from fractions import Fraction 

1981 >>> np.isscalar(Fraction(5, 17)) 

1982 True 

1983 >>> from numbers import Number 

1984 >>> np.isscalar(Number()) 

1985 True 

1986 

1987 """ 

1988 return (isinstance(element, generic) 

1989 or type(element) in ScalarType 

1990 or isinstance(element, numbers.Number)) 

1991 

1992 

1993@set_module('numpy') 

1994def binary_repr(num, width=None): 

1995 """ 

1996 Return the binary representation of the input number as a string. 

1997 

1998 For negative numbers, if width is not given, a minus sign is added to the 

1999 front. If width is given, the two's complement of the number is 

2000 returned, with respect to that width. 

2001 

2002 In a two's-complement system negative numbers are represented by the two's 

2003 complement of the absolute value. This is the most common method of 

2004 representing signed integers on computers [1]_. A N-bit two's-complement 

2005 system can represent every integer in the range 

2006 :math:`-2^{N-1}` to :math:`+2^{N-1}-1`. 

2007 

2008 Parameters 

2009 ---------- 

2010 num : int 

2011 Only an integer decimal number can be used. 

2012 width : int, optional 

2013 The length of the returned string if `num` is positive, or the length 

2014 of the two's complement if `num` is negative, provided that `width` is 

2015 at least a sufficient number of bits for `num` to be represented in 

2016 the designated form. If the `width` value is insufficient, an error is 

2017 raised. 

2018 

2019 Returns 

2020 ------- 

2021 bin : str 

2022 Binary representation of `num` or two's complement of `num`. 

2023 

2024 See Also 

2025 -------- 

2026 base_repr: Return a string representation of a number in the given base 

2027 system. 

2028 bin: Python's built-in binary representation generator of an integer. 

2029 

2030 Notes 

2031 ----- 

2032 `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x 

2033 faster. 

2034 

2035 References 

2036 ---------- 

2037 .. [1] Wikipedia, "Two's complement", 

2038 https://en.wikipedia.org/wiki/Two's_complement 

2039 

2040 Examples 

2041 -------- 

2042 >>> np.binary_repr(3) 

2043 '11' 

2044 >>> np.binary_repr(-3) 

2045 '-11' 

2046 >>> np.binary_repr(3, width=4) 

2047 '0011' 

2048 

2049 The two's complement is returned when the input number is negative and 

2050 width is specified: 

2051 

2052 >>> np.binary_repr(-3, width=3) 

2053 '101' 

2054 >>> np.binary_repr(-3, width=5) 

2055 '11101' 

2056 

2057 """ 

2058 def err_if_insufficient(width, binwidth): 

2059 if width is not None and width < binwidth: 

2060 raise ValueError( 

2061 f"Insufficient bit {width=} provided for {binwidth=}" 

2062 ) 

2063 

2064 # Ensure that num is a Python integer to avoid overflow or unwanted 

2065 # casts to floating point. 

2066 num = operator.index(num) 

2067 

2068 if num == 0: 

2069 return '0' * (width or 1) 

2070 

2071 elif num > 0: 

2072 binary = bin(num)[2:] 

2073 binwidth = len(binary) 

2074 outwidth = (binwidth if width is None 

2075 else builtins.max(binwidth, width)) 

2076 err_if_insufficient(width, binwidth) 

2077 return binary.zfill(outwidth) 

2078 

2079 else: 

2080 if width is None: 

2081 return '-' + bin(-num)[2:] 

2082 

2083 else: 

2084 poswidth = len(bin(-num)[2:]) 

2085 

2086 # See gh-8679: remove extra digit 

2087 # for numbers at boundaries. 

2088 if 2**(poswidth - 1) == -num: 

2089 poswidth -= 1 

2090 

2091 twocomp = 2**(poswidth + 1) + num 

2092 binary = bin(twocomp)[2:] 

2093 binwidth = len(binary) 

2094 

2095 outwidth = builtins.max(binwidth, width) 

2096 err_if_insufficient(width, binwidth) 

2097 return '1' * (outwidth - binwidth) + binary 

2098 

2099 

2100@set_module('numpy') 

2101def base_repr(number, base=2, padding=0): 

2102 """ 

2103 Return a string representation of a number in the given base system. 

2104 

2105 Parameters 

2106 ---------- 

2107 number : int 

2108 The value to convert. Positive and negative values are handled. 

2109 base : int, optional 

2110 Convert `number` to the `base` number system. The valid range is 2-36, 

2111 the default value is 2. 

2112 padding : int, optional 

2113 Number of zeros padded on the left. Default is 0 (no padding). 

2114 

2115 Returns 

2116 ------- 

2117 out : str 

2118 String representation of `number` in `base` system. 

2119 

2120 See Also 

2121 -------- 

2122 binary_repr : Faster version of `base_repr` for base 2. 

2123 

2124 Examples 

2125 -------- 

2126 >>> np.base_repr(5) 

2127 '101' 

2128 >>> np.base_repr(6, 5) 

2129 '11' 

2130 >>> np.base_repr(7, base=5, padding=3) 

2131 '00012' 

2132 

2133 >>> np.base_repr(10, base=16) 

2134 'A' 

2135 >>> np.base_repr(32, base=16) 

2136 '20' 

2137 

2138 """ 

2139 digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' 

2140 if base > len(digits): 

2141 raise ValueError("Bases greater than 36 not handled in base_repr.") 

2142 elif base < 2: 

2143 raise ValueError("Bases less than 2 not handled in base_repr.") 

2144 

2145 num = abs(int(number)) 

2146 res = [] 

2147 while num: 

2148 res.append(digits[num % base]) 

2149 num //= base 

2150 if padding: 

2151 res.append('0' * padding) 

2152 if number < 0: 

2153 res.append('-') 

2154 return ''.join(reversed(res or '0')) 

2155 

2156 

2157# These are all essentially abbreviations 

2158# These might wind up in a special abbreviations module 

2159 

2160 

2161def _maketup(descr, val): 

2162 dt = dtype(descr) 

2163 # Place val in all scalar tuples: 

2164 fields = dt.fields 

2165 if fields is None: 

2166 return val 

2167 else: 

2168 res = [_maketup(fields[name][0], val) for name in dt.names] 

2169 return tuple(res) 

2170 

2171 

2172@set_array_function_like_doc 

2173@set_module('numpy') 

2174def identity(n, dtype=None, *, like=None): 

2175 """ 

2176 Return the identity array. 

2177 

2178 The identity array is a square array with ones on 

2179 the main diagonal. 

2180 

2181 Parameters 

2182 ---------- 

2183 n : int 

2184 Number of rows (and columns) in `n` x `n` output. 

2185 dtype : data-type, optional 

2186 Data-type of the output. Defaults to ``float``. 

2187 ${ARRAY_FUNCTION_LIKE} 

2188 

2189 .. versionadded:: 1.20.0 

2190 

2191 Returns 

2192 ------- 

2193 out : ndarray 

2194 `n` x `n` array with its main diagonal set to one, 

2195 and all other elements 0. 

2196 

2197 Examples 

2198 -------- 

2199 >>> np.identity(3) 

2200 array([[1., 0., 0.], 

2201 [0., 1., 0.], 

2202 [0., 0., 1.]]) 

2203 

2204 """ 

2205 if like is not None: 

2206 return _identity_with_like(like, n, dtype=dtype) 

2207 

2208 from numpy import eye 

2209 return eye(n, dtype=dtype, like=like) 

2210 

2211 

2212_identity_with_like = array_function_dispatch()(identity) 

2213 

2214 

2215def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None): 

2216 return (a, b, rtol, atol) 

2217 

2218 

2219@array_function_dispatch(_allclose_dispatcher) 

2220def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): 

2221 """ 

2222 Returns True if two arrays are element-wise equal within a tolerance. 

2223 

2224 The tolerance values are positive, typically very small numbers. The 

2225 relative difference (`rtol` * abs(`b`)) and the absolute difference 

2226 `atol` are added together to compare against the absolute difference 

2227 between `a` and `b`. 

2228 

2229 .. warning:: The default `atol` is not appropriate for comparing numbers 

2230 with magnitudes much smaller than one (see Notes). 

2231 

2232 NaNs are treated as equal if they are in the same place and if 

2233 ``equal_nan=True``. Infs are treated as equal if they are in the same 

2234 place and of the same sign in both arrays. 

2235 

2236 Parameters 

2237 ---------- 

2238 a, b : array_like 

2239 Input arrays to compare. 

2240 rtol : array_like 

2241 The relative tolerance parameter (see Notes). 

2242 atol : array_like 

2243 The absolute tolerance parameter (see Notes). 

2244 equal_nan : bool 

2245 Whether to compare NaN's as equal. If True, NaN's in `a` will be 

2246 considered equal to NaN's in `b` in the output array. 

2247 

2248 .. versionadded:: 1.10.0 

2249 

2250 Returns 

2251 ------- 

2252 allclose : bool 

2253 Returns True if the two arrays are equal within the given 

2254 tolerance; False otherwise. 

2255 

2256 See Also 

2257 -------- 

2258 isclose, all, any, equal 

2259 

2260 Notes 

2261 ----- 

2262 If the following equation is element-wise True, then allclose returns 

2263 True.:: 

2264 

2265 absolute(a - b) <= (atol + rtol * absolute(b)) 

2266 

2267 The above equation is not symmetric in `a` and `b`, so that 

2268 ``allclose(a, b)`` might be different from ``allclose(b, a)`` in 

2269 some rare cases. 

2270 

2271 The default value of `atol` is not appropriate when the reference value 

2272 `b` has magnitude smaller than one. For example, it is unlikely that 

2273 ``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet 

2274 ``allclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure 

2275 to select `atol` for the use case at hand, especially for defining the 

2276 threshold below which a non-zero value in `a` will be considered "close" 

2277 to a very small or zero value in `b`. 

2278 

2279 The comparison of `a` and `b` uses standard broadcasting, which 

2280 means that `a` and `b` need not have the same shape in order for 

2281 ``allclose(a, b)`` to evaluate to True. The same is true for 

2282 `equal` but not `array_equal`. 

2283 

2284 `allclose` is not defined for non-numeric data types. 

2285 `bool` is considered a numeric data-type for this purpose. 

2286 

2287 Examples 

2288 -------- 

2289 >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8]) 

2290 False 

2291 >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9]) 

2292 True 

2293 >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9]) 

2294 False 

2295 >>> np.allclose([1.0, np.nan], [1.0, np.nan]) 

2296 False 

2297 >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) 

2298 True 

2299 

2300 """ 

2301 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)) 

2302 return builtins.bool(res) 

2303 

2304 

2305def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None): 

2306 return (a, b, rtol, atol) 

2307 

2308 

2309@array_function_dispatch(_isclose_dispatcher) 

2310def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): 

2311 """ 

2312 Returns a boolean array where two arrays are element-wise equal within a 

2313 tolerance. 

2314 

2315 The tolerance values are positive, typically very small numbers. The 

2316 relative difference (`rtol` * abs(`b`)) and the absolute difference 

2317 `atol` are added together to compare against the absolute difference 

2318 between `a` and `b`. 

2319 

2320 .. warning:: The default `atol` is not appropriate for comparing numbers 

2321 with magnitudes much smaller than one (see Notes). 

2322 

2323 Parameters 

2324 ---------- 

2325 a, b : array_like 

2326 Input arrays to compare. 

2327 rtol : array_like 

2328 The relative tolerance parameter (see Notes). 

2329 atol : array_like 

2330 The absolute tolerance parameter (see Notes). 

2331 equal_nan : bool 

2332 Whether to compare NaN's as equal. If True, NaN's in `a` will be 

2333 considered equal to NaN's in `b` in the output array. 

2334 

2335 Returns 

2336 ------- 

2337 y : array_like 

2338 Returns a boolean array of where `a` and `b` are equal within the 

2339 given tolerance. If both `a` and `b` are scalars, returns a single 

2340 boolean value. 

2341 

2342 See Also 

2343 -------- 

2344 allclose 

2345 math.isclose 

2346 

2347 Notes 

2348 ----- 

2349 .. versionadded:: 1.7.0 

2350 

2351 For finite values, isclose uses the following equation to test whether 

2352 two floating point values are equivalent.:: 

2353 

2354 absolute(a - b) <= (atol + rtol * absolute(b)) 

2355 

2356 Unlike the built-in `math.isclose`, the above equation is not symmetric 

2357 in `a` and `b` -- it assumes `b` is the reference value -- so that 

2358 `isclose(a, b)` might be different from `isclose(b, a)`. 

2359 

2360 The default value of `atol` is not appropriate when the reference value 

2361 `b` has magnitude smaller than one. For example, it is unlikely that 

2362 ``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet 

2363 ``isclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure 

2364 to select `atol` for the use case at hand, especially for defining the 

2365 threshold below which a non-zero value in `a` will be considered "close" 

2366 to a very small or zero value in `b`. 

2367 

2368 `isclose` is not defined for non-numeric data types. 

2369 :class:`bool` is considered a numeric data-type for this purpose. 

2370 

2371 Examples 

2372 -------- 

2373 >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8]) 

2374 array([ True, False]) 

2375 >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9]) 

2376 array([ True, True]) 

2377 >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9]) 

2378 array([False, True]) 

2379 >>> np.isclose([1.0, np.nan], [1.0, np.nan]) 

2380 array([ True, False]) 

2381 >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) 

2382 array([ True, True]) 

2383 >>> np.isclose([1e-8, 1e-7], [0.0, 0.0]) 

2384 array([ True, False]) 

2385 >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0) 

2386 array([False, False]) 

2387 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0]) 

2388 array([ True, True]) 

2389 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0) 

2390 array([False, True]) 

2391 """ 

2392 # Turn all but python scalars into arrays. 

2393 x, y, atol, rtol = ( 

2394 a if isinstance(a, (int, float, complex)) else asanyarray(a) 

2395 for a in (a, b, atol, rtol)) 

2396 

2397 # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT). 

2398 # This will cause casting of x later. Also, make sure to allow subclasses 

2399 # (e.g., for numpy.ma). 

2400 # NOTE: We explicitly allow timedelta, which used to work. This could 

2401 # possibly be deprecated. See also gh-18286. 

2402 # timedelta works if `atol` is an integer or also a timedelta. 

2403 # Although, the default tolerances are unlikely to be useful 

2404 if (dtype := getattr(y, "dtype", None)) is not None and dtype.kind != "m": 

2405 dt = multiarray.result_type(y, 1.) 

2406 y = asanyarray(y, dtype=dt) 

2407 elif isinstance(y, int): 

2408 y = float(y) 

2409 

2410 with errstate(invalid='ignore'), _no_nep50_warning(): 

2411 result = (less_equal(abs(x-y), atol + rtol * abs(y)) 

2412 & isfinite(y) 

2413 | (x == y)) 

2414 if equal_nan: 

2415 result |= isnan(x) & isnan(y) 

2416 

2417 return result[()] # Flatten 0d arrays to scalars 

2418 

2419 

2420def _array_equal_dispatcher(a1, a2, equal_nan=None): 

2421 return (a1, a2) 

2422 

2423 

2424_no_nan_types = { 

2425 # should use np.dtype.BoolDType, but as of writing 

2426 # that fails the reloading test. 

2427 type(dtype(nt.bool)), 

2428 type(dtype(nt.int8)), 

2429 type(dtype(nt.int16)), 

2430 type(dtype(nt.int32)), 

2431 type(dtype(nt.int64)), 

2432} 

2433 

2434 

2435def _dtype_cannot_hold_nan(dtype): 

2436 return type(dtype) in _no_nan_types 

2437 

2438 

2439@array_function_dispatch(_array_equal_dispatcher) 

2440def array_equal(a1, a2, equal_nan=False): 

2441 """ 

2442 True if two arrays have the same shape and elements, False otherwise. 

2443 

2444 Parameters 

2445 ---------- 

2446 a1, a2 : array_like 

2447 Input arrays. 

2448 equal_nan : bool 

2449 Whether to compare NaN's as equal. If the dtype of a1 and a2 is 

2450 complex, values will be considered equal if either the real or the 

2451 imaginary component of a given value is ``nan``. 

2452 

2453 .. versionadded:: 1.19.0 

2454 

2455 Returns 

2456 ------- 

2457 b : bool 

2458 Returns True if the arrays are equal. 

2459 

2460 See Also 

2461 -------- 

2462 allclose: Returns True if two arrays are element-wise equal within a 

2463 tolerance. 

2464 array_equiv: Returns True if input arrays are shape consistent and all 

2465 elements equal. 

2466 

2467 Examples 

2468 -------- 

2469 >>> np.array_equal([1, 2], [1, 2]) 

2470 True 

2471 >>> np.array_equal(np.array([1, 2]), np.array([1, 2])) 

2472 True 

2473 >>> np.array_equal([1, 2], [1, 2, 3]) 

2474 False 

2475 >>> np.array_equal([1, 2], [1, 4]) 

2476 False 

2477 >>> a = np.array([1, np.nan]) 

2478 >>> np.array_equal(a, a) 

2479 False 

2480 >>> np.array_equal(a, a, equal_nan=True) 

2481 True 

2482 

2483 When ``equal_nan`` is True, complex values with nan components are 

2484 considered equal if either the real *or* the imaginary components are nan. 

2485 

2486 >>> a = np.array([1 + 1j]) 

2487 >>> b = a.copy() 

2488 >>> a.real = np.nan 

2489 >>> b.imag = np.nan 

2490 >>> np.array_equal(a, b, equal_nan=True) 

2491 True 

2492 """ 

2493 try: 

2494 a1, a2 = asarray(a1), asarray(a2) 

2495 except Exception: 

2496 return False 

2497 if a1.shape != a2.shape: 

2498 return False 

2499 if not equal_nan: 

2500 return builtins.bool((a1 == a2).all()) 

2501 cannot_have_nan = (_dtype_cannot_hold_nan(a1.dtype) 

2502 and _dtype_cannot_hold_nan(a2.dtype)) 

2503 if cannot_have_nan: 

2504 if a1 is a2: 

2505 return True 

2506 return builtins.bool((a1 == a2).all()) 

2507 

2508 if a1 is a2: 

2509 # nan will compare equal so an array will compare equal to itself. 

2510 return True 

2511 # Handling NaN values if equal_nan is True 

2512 a1nan, a2nan = isnan(a1), isnan(a2) 

2513 # NaN's occur at different locations 

2514 if not (a1nan == a2nan).all(): 

2515 return False 

2516 # Shapes of a1, a2 and masks are guaranteed to be consistent by this point 

2517 return builtins.bool((a1[~a1nan] == a2[~a1nan]).all()) 

2518 

2519 

2520def _array_equiv_dispatcher(a1, a2): 

2521 return (a1, a2) 

2522 

2523 

2524@array_function_dispatch(_array_equiv_dispatcher) 

2525def array_equiv(a1, a2): 

2526 """ 

2527 Returns True if input arrays are shape consistent and all elements equal. 

2528 

2529 Shape consistent means they are either the same shape, or one input array 

2530 can be broadcasted to create the same shape as the other one. 

2531 

2532 Parameters 

2533 ---------- 

2534 a1, a2 : array_like 

2535 Input arrays. 

2536 

2537 Returns 

2538 ------- 

2539 out : bool 

2540 True if equivalent, False otherwise. 

2541 

2542 Examples 

2543 -------- 

2544 >>> np.array_equiv([1, 2], [1, 2]) 

2545 True 

2546 >>> np.array_equiv([1, 2], [1, 3]) 

2547 False 

2548 

2549 Showing the shape equivalence: 

2550 

2551 >>> np.array_equiv([1, 2], [[1, 2], [1, 2]]) 

2552 True 

2553 >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]]) 

2554 False 

2555 

2556 >>> np.array_equiv([1, 2], [[1, 2], [1, 3]]) 

2557 False 

2558 

2559 """ 

2560 try: 

2561 a1, a2 = asarray(a1), asarray(a2) 

2562 except Exception: 

2563 return False 

2564 try: 

2565 multiarray.broadcast(a1, a2) 

2566 except Exception: 

2567 return False 

2568 

2569 return builtins.bool((a1 == a2).all()) 

2570 

2571 

2572def _astype_dispatcher(x, dtype, /, *, copy=None): 

2573 return (x, dtype) 

2574 

2575 

2576@array_function_dispatch(_astype_dispatcher) 

2577def astype(x, dtype, /, *, copy = True): 

2578 """ 

2579 Copies an array to a specified data type. 

2580 

2581 This function is an Array API compatible alternative to 

2582 `numpy.ndarray.astype`. 

2583 

2584 Parameters 

2585 ---------- 

2586 x : ndarray 

2587 Input NumPy array to cast. ``array_likes`` are explicitly not 

2588 supported here. 

2589 dtype : dtype 

2590 Data type of the result. 

2591 copy : bool, optional 

2592 Specifies whether to copy an array when the specified dtype matches 

2593 the data type of the input array ``x``. If ``True``, a newly allocated 

2594 array must always be returned. If ``False`` and the specified dtype 

2595 matches the data type of the input array, the input array must be 

2596 returned; otherwise, a newly allocated array must be returned. 

2597 Defaults to ``True``. 

2598 

2599 Returns 

2600 ------- 

2601 out : ndarray 

2602 An array having the specified data type. 

2603 

2604 See Also 

2605 -------- 

2606 ndarray.astype 

2607 

2608 Examples 

2609 -------- 

2610 >>> arr = np.array([1, 2, 3]); arr 

2611 array([1, 2, 3]) 

2612 >>> np.astype(arr, np.float64) 

2613 array([1., 2., 3.]) 

2614 

2615 Non-copy case: 

2616 

2617 >>> arr = np.array([1, 2, 3]) 

2618 >>> arr_noncpy = np.astype(arr, arr.dtype, copy=False) 

2619 >>> np.shares_memory(arr, arr_noncpy) 

2620 True 

2621 

2622 """ 

2623 if not isinstance(x, np.ndarray): 

2624 raise TypeError( 

2625 f"Input should be a NumPy array. It is a {type(x)} instead." 

2626 ) 

2627 return x.astype(dtype, copy=copy) 

2628 

2629 

2630inf = PINF 

2631nan = NAN 

2632False_ = nt.bool(False) 

2633True_ = nt.bool(True) 

2634 

2635 

2636def extend_all(module): 

2637 existing = set(__all__) 

2638 mall = getattr(module, '__all__') 

2639 for a in mall: 

2640 if a not in existing: 

2641 __all__.append(a) 

2642 

2643 

2644from .umath import * 

2645from .numerictypes import * 

2646from . import fromnumeric 

2647from .fromnumeric import * 

2648from . import arrayprint 

2649from .arrayprint import * 

2650from . import _asarray 

2651from ._asarray import * 

2652from . import _ufunc_config 

2653from ._ufunc_config import * 

2654extend_all(fromnumeric) 

2655extend_all(umath) 

2656extend_all(numerictypes) 

2657extend_all(arrayprint) 

2658extend_all(_asarray) 

2659extend_all(_ufunc_config)