Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/numpy/core/numeric.py: 29%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

495 statements  

1import functools 

2import itertools 

3import operator 

4import sys 

5import warnings 

6import numbers 

7 

8import numpy as np 

9from . import multiarray 

10from .multiarray import ( 

11 fastCopyAndTranspose, ALLOW_THREADS, 

12 BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE, 

13 WRAP, arange, array, asarray, asanyarray, ascontiguousarray, 

14 asfortranarray, broadcast, can_cast, compare_chararrays, 

15 concatenate, copyto, dot, dtype, empty, 

16 empty_like, flatiter, frombuffer, from_dlpack, fromfile, fromiter, 

17 fromstring, inner, lexsort, matmul, may_share_memory, 

18 min_scalar_type, ndarray, nditer, nested_iters, promote_types, 

19 putmask, result_type, set_numeric_ops, shares_memory, vdot, where, 

20 zeros, normalize_axis_index, _get_promotion_state, _set_promotion_state) 

21 

22from . import overrides 

23from . import umath 

24from . import shape_base 

25from .overrides import set_array_function_like_doc, set_module 

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

27from . import numerictypes 

28from .numerictypes import longlong, intc, int_, float_, complex_, bool_ 

29from ._exceptions import TooHardError, AxisError 

30from ._ufunc_config import errstate, _no_nep50_warning 

31 

32bitwise_not = invert 

33ufunc = type(sin) 

34newaxis = None 

35 

36array_function_dispatch = functools.partial( 

37 overrides.array_function_dispatch, module='numpy') 

38 

39 

40__all__ = [ 

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

42 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray', 

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

44 'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where', 

45 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort', 

46 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type', 

47 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', 

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

49 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 

50 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 

51 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones', 

52 'identity', 'allclose', 'compare_chararrays', 'putmask', 

53 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN', 

54 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', 

55 'BUFSIZE', 'ALLOW_THREADS', 'ComplexWarning', 'full', 'full_like', 

56 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS', 

57 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError', 

58 '_get_promotion_state', '_set_promotion_state'] 

59 

60 

61@set_module('numpy') 

62class ComplexWarning(RuntimeWarning): 

63 """ 

64 The warning raised when casting a complex dtype to a real dtype. 

65 

66 As implemented, casting a complex number to a real discards its imaginary 

67 part, but this behavior may not be what the user actually wants. 

68 

69 """ 

70 pass 

71 

72 

73def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None): 

74 return (a,) 

75 

76 

77@array_function_dispatch(_zeros_like_dispatcher) 

78def zeros_like(a, dtype=None, order='K', subok=True, shape=None): 

79 """ 

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

81 

82 Parameters 

83 ---------- 

84 a : array_like 

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

86 the returned array. 

87 dtype : data-type, optional 

88 Overrides the data type of the result. 

89 

90 .. versionadded:: 1.6.0 

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

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

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

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

95 as possible. 

96 

97 .. versionadded:: 1.6.0 

98 subok : bool, optional. 

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

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

101 to True. 

102 shape : int or sequence of ints, optional. 

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

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

105 order='C' is implied. 

106 

107 .. versionadded:: 1.17.0 

108 

109 Returns 

110 ------- 

111 out : ndarray 

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

113 

114 See Also 

115 -------- 

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

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

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

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

120 

121 Examples 

122 -------- 

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

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

125 >>> x 

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

127 [3, 4, 5]]) 

128 >>> np.zeros_like(x) 

129 array([[0, 0, 0], 

130 [0, 0, 0]]) 

131 

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

133 >>> y 

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

135 >>> np.zeros_like(y) 

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

137 

138 """ 

139 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) 

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

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

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

143 return res 

144 

145 

146def _ones_dispatcher(shape, dtype=None, order=None, *, like=None): 

147 return(like,) 

148 

149 

150@set_array_function_like_doc 

151@set_module('numpy') 

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

153 """ 

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

155 

156 Parameters 

157 ---------- 

158 shape : int or sequence of ints 

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

160 dtype : data-type, optional 

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

162 `numpy.float64`. 

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

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

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

166 memory. 

167 ${ARRAY_FUNCTION_LIKE} 

168 

169 .. versionadded:: 1.20.0 

170 

171 Returns 

172 ------- 

173 out : ndarray 

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

175 

176 See Also 

177 -------- 

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

179 empty : Return a new uninitialized array. 

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

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

182 

183 

184 Examples 

185 -------- 

186 >>> np.ones(5) 

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

188 

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

190 array([1, 1, 1, 1, 1]) 

191 

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

193 array([[1.], 

194 [1.]]) 

195 

196 >>> s = (2,2) 

197 >>> np.ones(s) 

198 array([[1., 1.], 

199 [1., 1.]]) 

200 

201 """ 

202 if like is not None: 

203 return _ones_with_like(shape, dtype=dtype, order=order, like=like) 

204 

205 a = empty(shape, dtype, order) 

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

207 return a 

208 

209 

210_ones_with_like = array_function_dispatch( 

211 _ones_dispatcher, use_like=True 

212)(ones) 

213 

214 

215def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None): 

216 return (a,) 

217 

218 

219@array_function_dispatch(_ones_like_dispatcher) 

220def ones_like(a, dtype=None, order='K', subok=True, shape=None): 

221 """ 

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

223 

224 Parameters 

225 ---------- 

226 a : array_like 

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

228 the returned array. 

229 dtype : data-type, optional 

230 Overrides the data type of the result. 

231 

232 .. versionadded:: 1.6.0 

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

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

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

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

237 as possible. 

238 

239 .. versionadded:: 1.6.0 

240 subok : bool, optional. 

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

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

243 to True. 

244 shape : int or sequence of ints, optional. 

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

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

247 order='C' is implied. 

248 

249 .. versionadded:: 1.17.0 

250 

251 Returns 

252 ------- 

253 out : ndarray 

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

255 

256 See Also 

257 -------- 

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

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

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

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

262 

263 Examples 

264 -------- 

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

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

267 >>> x 

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

269 [3, 4, 5]]) 

270 >>> np.ones_like(x) 

271 array([[1, 1, 1], 

272 [1, 1, 1]]) 

273 

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

275 >>> y 

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

277 >>> np.ones_like(y) 

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

279 

280 """ 

281 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) 

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

283 return res 

284 

285 

286def _full_dispatcher(shape, fill_value, dtype=None, order=None, *, like=None): 

287 return(like,) 

288 

289 

290@set_array_function_like_doc 

291@set_module('numpy') 

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

293 """ 

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

295 

296 Parameters 

297 ---------- 

298 shape : int or sequence of ints 

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

300 fill_value : scalar or array_like 

301 Fill value. 

302 dtype : data-type, optional 

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

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

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

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

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

308 ${ARRAY_FUNCTION_LIKE} 

309 

310 .. versionadded:: 1.20.0 

311 

312 Returns 

313 ------- 

314 out : ndarray 

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

316 

317 See Also 

318 -------- 

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

320 empty : Return a new uninitialized array. 

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

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

323 

324 Examples 

325 -------- 

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

327 array([[inf, inf], 

328 [inf, inf]]) 

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

330 array([[10, 10], 

331 [10, 10]]) 

332 

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

334 array([[1, 2], 

335 [1, 2]]) 

336 

337 """ 

338 if like is not None: 

339 return _full_with_like(shape, fill_value, dtype=dtype, order=order, like=like) 

340 

341 if dtype is None: 

342 fill_value = asarray(fill_value) 

343 dtype = fill_value.dtype 

344 a = empty(shape, dtype, order) 

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

346 return a 

347 

348 

349_full_with_like = array_function_dispatch( 

350 _full_dispatcher, use_like=True 

351)(full) 

352 

353 

354def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None): 

355 return (a,) 

356 

357 

358@array_function_dispatch(_full_like_dispatcher) 

359def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None): 

360 """ 

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

362 

363 Parameters 

364 ---------- 

365 a : array_like 

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

367 the returned array. 

368 fill_value : array_like 

369 Fill value. 

370 dtype : data-type, optional 

371 Overrides the data type of the result. 

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

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

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

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

376 as possible. 

377 subok : bool, optional. 

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

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

380 to True. 

381 shape : int or sequence of ints, optional. 

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

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

384 order='C' is implied. 

385 

386 .. versionadded:: 1.17.0 

387 

388 Returns 

389 ------- 

390 out : ndarray 

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

392 

393 See Also 

394 -------- 

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

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

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

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

399 

400 Examples 

401 -------- 

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

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

404 array([1, 1, 1, 1, 1, 1]) 

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

406 array([0, 0, 0, 0, 0, 0]) 

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

408 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) 

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

410 array([nan, nan, nan, nan, nan, nan]) 

411 

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

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

414 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) 

415 

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

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

418 array([[[ 0, 0, 255], 

419 [ 0, 0, 255]], 

420 [[ 0, 0, 255], 

421 [ 0, 0, 255]]]) 

422 """ 

423 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) 

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

425 return res 

426 

427 

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

429 return (a,) 

430 

431 

432@array_function_dispatch(_count_nonzero_dispatcher) 

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

434 """ 

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

436 

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

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

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

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

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

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

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

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

445 method evaluated to ``True``. 

446 

447 Parameters 

448 ---------- 

449 a : array_like 

450 The array for which to count non-zeros. 

451 axis : int or tuple, optional 

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

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

454 along a flattened version of ``a``. 

455 

456 .. versionadded:: 1.12.0 

457 

458 keepdims : bool, optional 

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

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

461 the result will broadcast correctly against the input array. 

462 

463 .. versionadded:: 1.19.0 

464 

465 Returns 

466 ------- 

467 count : int or array of int 

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

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

470 is returned. 

471 

472 See Also 

473 -------- 

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

475 

476 Examples 

477 -------- 

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

479 4 

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

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

482 >>> np.count_nonzero(a) 

483 5 

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

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

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

487 array([2, 3]) 

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

489 array([[2], 

490 [3]]) 

491 """ 

492 if axis is None and not keepdims: 

493 return multiarray.count_nonzero(a) 

494 

495 a = asanyarray(a) 

496 

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

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

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

500 else: 

501 a_bool = a.astype(np.bool_, copy=False) 

502 

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

504 

505 

506@set_module('numpy') 

507def isfortran(a): 

508 """ 

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

510 

511 This function is obsolete and, because of changes due to relaxed stride 

512 checking, its return value for the same array may differ for versions 

513 of NumPy >= 1.10.0 and previous versions. If you only want to check if an 

514 array is Fortran contiguous use ``a.flags.f_contiguous`` instead. 

515 

516 Parameters 

517 ---------- 

518 a : ndarray 

519 Input array. 

520 

521 Returns 

522 ------- 

523 isfortran : bool 

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

525 

526 

527 Examples 

528 -------- 

529 

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

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

532 memory (first index varies the fastest). 

533 

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

535 >>> a 

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

537 [4, 5, 6]]) 

538 >>> np.isfortran(a) 

539 False 

540 

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

542 >>> b 

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

544 [4, 5, 6]]) 

545 >>> np.isfortran(b) 

546 True 

547 

548 

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

550 

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

552 >>> a 

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

554 [4, 5, 6]]) 

555 >>> np.isfortran(a) 

556 False 

557 >>> b = a.T 

558 >>> b 

559 array([[1, 4], 

560 [2, 5], 

561 [3, 6]]) 

562 >>> np.isfortran(b) 

563 True 

564 

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

566 

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

568 False 

569 

570 """ 

571 return a.flags.fnc 

572 

573 

574def _argwhere_dispatcher(a): 

575 return (a,) 

576 

577 

578@array_function_dispatch(_argwhere_dispatcher) 

579def argwhere(a): 

580 """ 

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

582 

583 Parameters 

584 ---------- 

585 a : array_like 

586 Input data. 

587 

588 Returns 

589 ------- 

590 index_array : (N, a.ndim) ndarray 

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

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

593 non-zero items. 

594 

595 See Also 

596 -------- 

597 where, nonzero 

598 

599 Notes 

600 ----- 

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

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

603 

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

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

606 

607 Examples 

608 -------- 

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

610 >>> x 

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

612 [3, 4, 5]]) 

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

614 array([[0, 2], 

615 [1, 0], 

616 [1, 1], 

617 [1, 2]]) 

618 

619 """ 

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

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

622 a = shape_base.atleast_1d(a) 

623 # then remove the added dimension 

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

625 return transpose(nonzero(a)) 

626 

627 

628def _flatnonzero_dispatcher(a): 

629 return (a,) 

630 

631 

632@array_function_dispatch(_flatnonzero_dispatcher) 

633def flatnonzero(a): 

634 """ 

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

636 

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

638 

639 Parameters 

640 ---------- 

641 a : array_like 

642 Input data. 

643 

644 Returns 

645 ------- 

646 res : ndarray 

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

648 that are non-zero. 

649 

650 See Also 

651 -------- 

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

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

654 

655 Examples 

656 -------- 

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

658 >>> x 

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

660 >>> np.flatnonzero(x) 

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

662 

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

664 these elements: 

665 

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

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

668 

669 """ 

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

671 

672 

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

674 return (a, v) 

675 

676 

677@array_function_dispatch(_correlate_dispatcher) 

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

679 r""" 

680 Cross-correlation of two 1-dimensional sequences. 

681 

682 This function computes the correlation as generally defined in signal 

683 processing texts: 

684 

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

686 

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

688 :math:`\overline x` denoting complex conjugation. 

689 

690 Parameters 

691 ---------- 

692 a, v : array_like 

693 Input sequences. 

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

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

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

697 old_behavior : bool 

698 `old_behavior` was removed in NumPy 1.10. If you need the old 

699 behavior, use `multiarray.correlate`. 

700 

701 Returns 

702 ------- 

703 out : ndarray 

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

705 

706 See Also 

707 -------- 

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

709 multiarray.correlate : Old, no conjugate, version of correlate. 

710 scipy.signal.correlate : uses FFT which has superior performance on large arrays.  

711 

712 Notes 

713 ----- 

714 The definition of correlation above is not unique and sometimes correlation 

715 may be defined differently. Another common definition is: 

716 

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

718 

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

720 

721 `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5) because it does 

722 not use the FFT to compute the convolution; in that case, `scipy.signal.correlate` might 

723 be preferable. 

724  

725 

726 Examples 

727 -------- 

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

729 array([3.5]) 

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

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

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

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

734 

735 Using complex sequences: 

736 

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

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

739 

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

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

742 places: 

743 

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

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

746 

747 """ 

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

749 

750 

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

752 return (a, v) 

753 

754 

755@array_function_dispatch(_convolve_dispatcher) 

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

757 """ 

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

759 

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

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

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

763 distributed according to the convolution of their individual 

764 distributions. 

765 

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

767 

768 Parameters 

769 ---------- 

770 a : (N,) array_like 

771 First one-dimensional input array. 

772 v : (M,) array_like 

773 Second one-dimensional input array. 

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

775 'full': 

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

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

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

779 completely, and boundary effects may be seen. 

780 

781 'same': 

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

783 effects are still visible. 

784 

785 'valid': 

786 Mode 'valid' returns output of length 

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

788 for points where the signals overlap completely. Values outside 

789 the signal boundary have no effect. 

790 

791 Returns 

792 ------- 

793 out : ndarray 

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

795 

796 See Also 

797 -------- 

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

799 Transform. 

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

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

802 accepts poly1d objects as input. 

803 

804 Notes 

805 ----- 

806 The discrete convolution operation is defined as 

807 

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

809 

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

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

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

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

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

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

816 

817 References 

818 ---------- 

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

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

821 

822 Examples 

823 -------- 

824 Note how the convolution operator flips the second array 

825 before "sliding" the two across one another: 

826 

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

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

829 

830 Only return the middle values of the convolution. 

831 Contains boundary effects, where zeros are taken 

832 into account: 

833 

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

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

836 

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

838 is only one position where they completely overlap: 

839 

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

841 array([2.5]) 

842 

843 """ 

844 a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1) 

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

846 a, v = v, a 

847 if len(a) == 0: 

848 raise ValueError('a cannot be empty') 

849 if len(v) == 0: 

850 raise ValueError('v cannot be empty') 

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

852 

853 

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

855 return (a, b, out) 

856 

857 

858@array_function_dispatch(_outer_dispatcher) 

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

860 """ 

861 Compute the outer product of two vectors. 

862 

863 Given two vectors, ``a = [a0, a1, ..., aM]`` and 

864 ``b = [b0, b1, ..., bN]``, 

865 the outer product [1]_ is:: 

866 

867 [[a0*b0 a0*b1 ... a0*bN ] 

868 [a1*b0 . 

869 [ ... . 

870 [aM*b0 aM*bN ]] 

871 

872 Parameters 

873 ---------- 

874 a : (M,) array_like 

875 First input vector. Input is flattened if 

876 not already 1-dimensional. 

877 b : (N,) array_like 

878 Second input vector. Input is flattened if 

879 not already 1-dimensional. 

880 out : (M, N) ndarray, optional 

881 A location where the result is stored 

882 

883 .. versionadded:: 1.9.0 

884 

885 Returns 

886 ------- 

887 out : (M, N) ndarray 

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

889 

890 See also 

891 -------- 

892 inner 

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

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

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

896 is the equivalent. 

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

898 is the equivalent. 

899 

900 References 

901 ---------- 

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

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

904 pg. 8. 

905 

906 Examples 

907 -------- 

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

909 

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

911 >>> rl 

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

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

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

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

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

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

918 >>> im 

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

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

921 [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], 

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

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

924 >>> grid = rl + im 

925 >>> grid 

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

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

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

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

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

931 

932 An example using a "vector" of letters: 

933 

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

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

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

937 ['b', 'bb', 'bbb'], 

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

939 

940 """ 

941 a = asarray(a) 

942 b = asarray(b) 

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

944 

945 

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

947 return (a, b) 

948 

949 

950@array_function_dispatch(_tensordot_dispatcher) 

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

952 """ 

953 Compute tensor dot product along specified axes. 

954 

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

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

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

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

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

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

961 

962 Parameters 

963 ---------- 

964 a, b : array_like 

965 Tensors to "dot". 

966 

967 axes : int or (2,) array_like 

968 * integer_like 

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

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

971 * (2,) array_like 

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

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

974 

975 Returns 

976 ------- 

977 output : ndarray 

978 The tensor dot product of the input. 

979 

980 See Also 

981 -------- 

982 dot, einsum 

983 

984 Notes 

985 ----- 

986 Three common use cases are: 

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

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

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

990 

991 When `axes` is integer_like, the sequence for evaluation will be: first 

992 the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and 

993 Nth axis in `b` last. 

994 

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

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

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

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

999 

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

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

1002 

1003 Examples 

1004 -------- 

1005 A "traditional" example: 

1006 

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

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

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

1010 >>> c.shape 

1011 (5, 2) 

1012 >>> c 

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

1014 [4532., 4874.], 

1015 [4664., 5018.], 

1016 [4796., 5162.], 

1017 [4928., 5306.]]) 

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

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

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

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

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

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

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

1025 >>> c == d 

1026 array([[ True, True], 

1027 [ True, True], 

1028 [ True, True], 

1029 [ True, True], 

1030 [ True, True]]) 

1031 

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

1033 

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

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

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

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

1038 >>> a; A 

1039 array([[[1, 2], 

1040 [3, 4]], 

1041 [[5, 6], 

1042 [7, 8]]]) 

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

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

1045 

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

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

1048 

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

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

1051 ['aaacccc', 'bbbdddd']], 

1052 [['aaaaacccccc', 'bbbbbdddddd'], 

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

1054 

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

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

1057 ['c', 'd']], 

1058 ... 

1059 

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

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

1062 ['aabbbbbb', 'ccdddddd']], 

1063 [['aaabbbbbbb', 'cccddddddd'], 

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

1065 

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

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

1068 ['aaabbbb', 'cccdddd']], 

1069 [['aaaaabbbbbb', 'cccccdddddd'], 

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

1071 

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

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

1074 

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

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

1077 

1078 """ 

1079 try: 

1080 iter(axes) 

1081 except Exception: 

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

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

1084 else: 

1085 axes_a, axes_b = axes 

1086 try: 

1087 na = len(axes_a) 

1088 axes_a = list(axes_a) 

1089 except TypeError: 

1090 axes_a = [axes_a] 

1091 na = 1 

1092 try: 

1093 nb = len(axes_b) 

1094 axes_b = list(axes_b) 

1095 except TypeError: 

1096 axes_b = [axes_b] 

1097 nb = 1 

1098 

1099 a, b = asarray(a), asarray(b) 

1100 as_ = a.shape 

1101 nda = a.ndim 

1102 bs = b.shape 

1103 ndb = b.ndim 

1104 equal = True 

1105 if na != nb: 

1106 equal = False 

1107 else: 

1108 for k in range(na): 

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

1110 equal = False 

1111 break 

1112 if axes_a[k] < 0: 

1113 axes_a[k] += nda 

1114 if axes_b[k] < 0: 

1115 axes_b[k] += ndb 

1116 if not equal: 

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

1118 

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

1120 # and to the front of "b" 

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

1122 newaxes_a = notin + axes_a 

1123 N2 = 1 

1124 for axis in axes_a: 

1125 N2 *= as_[axis] 

1126 newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2) 

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

1128 

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

1130 newaxes_b = axes_b + notin 

1131 N2 = 1 

1132 for axis in axes_b: 

1133 N2 *= bs[axis] 

1134 newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin]))) 

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

1136 

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

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

1139 res = dot(at, bt) 

1140 return res.reshape(olda + oldb) 

1141 

1142 

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

1144 return (a,) 

1145 

1146 

1147@array_function_dispatch(_roll_dispatcher) 

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

1149 """ 

1150 Roll array elements along a given axis. 

1151 

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

1153 the first. 

1154 

1155 Parameters 

1156 ---------- 

1157 a : array_like 

1158 Input array. 

1159 shift : int or tuple of ints 

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

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

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

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

1164 all given axes. 

1165 axis : int or tuple of ints, optional 

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

1167 array is flattened before shifting, after which the original 

1168 shape is restored. 

1169 

1170 Returns 

1171 ------- 

1172 res : ndarray 

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

1174 

1175 See Also 

1176 -------- 

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

1178 given position. 

1179 

1180 Notes 

1181 ----- 

1182 .. versionadded:: 1.12.0 

1183 

1184 Supports rolling over multiple dimensions simultaneously. 

1185 

1186 Examples 

1187 -------- 

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

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

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

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

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

1193 

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

1195 >>> x2 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1222 

1223 """ 

1224 a = asanyarray(a) 

1225 if axis is None: 

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

1227 

1228 else: 

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

1230 broadcasted = broadcast(shift, axis) 

1231 if broadcasted.ndim > 1: 

1232 raise ValueError( 

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

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

1235 for sh, ax in broadcasted: 

1236 shifts[ax] += sh 

1237 

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

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

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

1241 if offset: 

1242 # (original, result), (original, result) 

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

1244 (slice(-offset, None), slice(None, offset))) 

1245 

1246 result = empty_like(a) 

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

1248 arr_index, res_index = zip(*indices) 

1249 result[res_index] = a[arr_index] 

1250 

1251 return result 

1252 

1253 

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

1255 return (a,) 

1256 

1257 

1258@array_function_dispatch(_rollaxis_dispatcher) 

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

1260 """ 

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

1262 

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

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

1265 1.11. 

1266 

1267 Parameters 

1268 ---------- 

1269 a : ndarray 

1270 Input array. 

1271 axis : int 

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

1273 change relative to one another. 

1274 start : int, optional 

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

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

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

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

1279 are interpreted: 

1280 

1281 .. table:: 

1282 :align: left 

1283 

1284 +-------------------+----------------------+ 

1285 | ``start`` | Normalized ``start`` | 

1286 +===================+======================+ 

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

1288 +-------------------+----------------------+ 

1289 | ``-arr.ndim`` | 0 | 

1290 +-------------------+----------------------+ 

1291 | |vdots| | |vdots| | 

1292 +-------------------+----------------------+ 

1293 | ``-1`` | ``arr.ndim-1`` | 

1294 +-------------------+----------------------+ 

1295 | ``0`` | ``0`` | 

1296 +-------------------+----------------------+ 

1297 | |vdots| | |vdots| | 

1298 +-------------------+----------------------+ 

1299 | ``arr.ndim`` | ``arr.ndim`` | 

1300 +-------------------+----------------------+ 

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

1302 +-------------------+----------------------+ 

1303  

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

1305 

1306 Returns 

1307 ------- 

1308 res : ndarray 

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

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

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

1312 

1313 See Also 

1314 -------- 

1315 moveaxis : Move array axes to new positions. 

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

1317 given axis. 

1318 

1319 Examples 

1320 -------- 

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

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

1323 (3, 6, 4, 5) 

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

1325 (5, 3, 4, 6) 

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

1327 (3, 5, 6, 4) 

1328 

1329 """ 

1330 n = a.ndim 

1331 axis = normalize_axis_index(axis, n) 

1332 if start < 0: 

1333 start += n 

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

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

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

1337 if axis < start: 

1338 # it's been removed 

1339 start -= 1 

1340 if axis == start: 

1341 return a[...] 

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

1343 axes.remove(axis) 

1344 axes.insert(start, axis) 

1345 return a.transpose(axes) 

1346 

1347 

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

1349 """ 

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

1351 

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

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

1354 `normalize_axis_index`. 

1355 

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

1357 

1358 Used internally by multi-axis-checking logic. 

1359 

1360 .. versionadded:: 1.13.0 

1361 

1362 Parameters 

1363 ---------- 

1364 axis : int, iterable of int 

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

1366 ndim : int 

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

1368 against. 

1369 argname : str, optional 

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

1371 argument. 

1372 allow_duplicate : bool, optional 

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

1374 

1375 Returns 

1376 ------- 

1377 normalized_axes : tuple of int 

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

1379 

1380 Raises 

1381 ------ 

1382 AxisError 

1383 If any axis provided is out of range 

1384 ValueError 

1385 If an axis is repeated 

1386 

1387 See also 

1388 -------- 

1389 normalize_axis_index : normalizing a single scalar axis 

1390 """ 

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

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

1393 try: 

1394 axis = [operator.index(axis)] 

1395 except TypeError: 

1396 pass 

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

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

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

1400 if argname: 

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

1402 else: 

1403 raise ValueError('repeated axis') 

1404 return axis 

1405 

1406 

1407def _moveaxis_dispatcher(a, source, destination): 

1408 return (a,) 

1409 

1410 

1411@array_function_dispatch(_moveaxis_dispatcher) 

1412def moveaxis(a, source, destination): 

1413 """ 

1414 Move axes of an array to new positions. 

1415 

1416 Other axes remain in their original order. 

1417 

1418 .. versionadded:: 1.11.0 

1419 

1420 Parameters 

1421 ---------- 

1422 a : np.ndarray 

1423 The array whose axes should be reordered. 

1424 source : int or sequence of int 

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

1426 destination : int or sequence of int 

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

1428 unique. 

1429 

1430 Returns 

1431 ------- 

1432 result : np.ndarray 

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

1434 

1435 See Also 

1436 -------- 

1437 transpose : Permute the dimensions of an array. 

1438 swapaxes : Interchange two axes of an array. 

1439 

1440 Examples 

1441 -------- 

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

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

1444 (4, 5, 3) 

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

1446 (5, 3, 4) 

1447 

1448 These all achieve the same result: 

1449 

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

1451 (5, 4, 3) 

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

1453 (5, 4, 3) 

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

1455 (5, 4, 3) 

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

1457 (5, 4, 3) 

1458 

1459 """ 

1460 try: 

1461 # allow duck-array types if they define transpose 

1462 transpose = a.transpose 

1463 except AttributeError: 

1464 a = asarray(a) 

1465 transpose = a.transpose 

1466 

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

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

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

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

1471 'the same number of elements') 

1472 

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

1474 

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

1476 order.insert(dest, src) 

1477 

1478 result = transpose(order) 

1479 return result 

1480 

1481 

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

1483 return (a, b) 

1484 

1485 

1486@array_function_dispatch(_cross_dispatcher) 

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

1488 """ 

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

1490 

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

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

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

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

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

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

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

1498 

1499 Parameters 

1500 ---------- 

1501 a : array_like 

1502 Components of the first vector(s). 

1503 b : array_like 

1504 Components of the second vector(s). 

1505 axisa : int, optional 

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

1507 axisb : int, optional 

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

1509 axisc : int, optional 

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

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

1512 By default, the last axis. 

1513 axis : int, optional 

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

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

1516 

1517 Returns 

1518 ------- 

1519 c : ndarray 

1520 Vector cross product(s). 

1521 

1522 Raises 

1523 ------ 

1524 ValueError 

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

1526 equal 2 or 3. 

1527 

1528 See Also 

1529 -------- 

1530 inner : Inner product 

1531 outer : Outer product. 

1532 ix_ : Construct index arrays. 

1533 

1534 Notes 

1535 ----- 

1536 .. versionadded:: 1.9.0 

1537 

1538 Supports full broadcasting of the inputs. 

1539 

1540 Examples 

1541 -------- 

1542 Vector cross-product. 

1543 

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

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

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

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

1548 

1549 One vector with dimension 2. 

1550 

1551 >>> x = [1, 2] 

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

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

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

1555 

1556 Equivalently: 

1557 

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

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

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

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

1562 

1563 Both vectors with dimension 2. 

1564 

1565 >>> x = [1,2] 

1566 >>> y = [4,5] 

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

1568 array(-3) 

1569 

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

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

1572 

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

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

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

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

1577 [ 3, -6, 3]]) 

1578 

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

1580 

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

1582 array([[-3, 3], 

1583 [ 6, -6], 

1584 [-3, 3]]) 

1585 

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

1587 

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

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

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

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

1592 [ 0, 0, 0], 

1593 [ 6, -12, 6]]) 

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

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

1596 [-30, 60, -30], 

1597 [-36, 72, -36]]) 

1598 

1599 """ 

1600 if axis is not None: 

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

1602 a = asarray(a) 

1603 b = asarray(b) 

1604 # Check axisa and axisb are within bounds 

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

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

1607 

1608 # Move working axis to the end of the shape 

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

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

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

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

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

1614 raise ValueError(msg) 

1615 

1616 # Create the output array 

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

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

1619 shape += (3,) 

1620 # Check axisc is within bounds 

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

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

1623 cp = empty(shape, dtype) 

1624 

1625 # recast arrays as dtype 

1626 a = a.astype(dtype) 

1627 b = b.astype(dtype) 

1628 

1629 # create local aliases for readability 

1630 a0 = a[..., 0] 

1631 a1 = a[..., 1] 

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

1633 a2 = a[..., 2] 

1634 b0 = b[..., 0] 

1635 b1 = b[..., 1] 

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

1637 b2 = b[..., 2] 

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

1639 cp0 = cp[..., 0] 

1640 cp1 = cp[..., 1] 

1641 cp2 = cp[..., 2] 

1642 

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

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

1645 # a0 * b1 - a1 * b0 

1646 multiply(a0, b1, out=cp) 

1647 cp -= a1 * b0 

1648 return cp 

1649 else: 

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

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

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

1653 # cp2 = a0 * b1 - a1 * b0 

1654 multiply(a1, b2, out=cp0) 

1655 multiply(a0, b2, out=cp1) 

1656 negative(cp1, out=cp1) 

1657 multiply(a0, b1, out=cp2) 

1658 cp2 -= a1 * b0 

1659 else: 

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

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

1662 # cp0 = a1 * b2 - a2 * b1 

1663 # cp1 = a2 * b0 - a0 * b2 

1664 # cp2 = a0 * b1 - a1 * b0 

1665 multiply(a1, b2, out=cp0) 

1666 tmp = array(a2 * b1) 

1667 cp0 -= tmp 

1668 multiply(a2, b0, out=cp1) 

1669 multiply(a0, b2, out=tmp) 

1670 cp1 -= tmp 

1671 multiply(a0, b1, out=cp2) 

1672 multiply(a1, b0, out=tmp) 

1673 cp2 -= tmp 

1674 else: 

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

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

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

1678 # cp2 = a0 * b1 - a1 * b0 

1679 multiply(a2, b1, out=cp0) 

1680 negative(cp0, out=cp0) 

1681 multiply(a2, b0, out=cp1) 

1682 multiply(a0, b1, out=cp2) 

1683 cp2 -= a1 * b0 

1684 

1685 return moveaxis(cp, -1, axisc) 

1686 

1687 

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

1689 

1690 

1691@set_module('numpy') 

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

1693 """ 

1694 Return an array representing the indices of a grid. 

1695 

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

1697 varying only along the corresponding axis. 

1698 

1699 Parameters 

1700 ---------- 

1701 dimensions : sequence of ints 

1702 The shape of the grid. 

1703 dtype : dtype, optional 

1704 Data type of the result. 

1705 sparse : boolean, optional 

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

1707 representation. Default is False. 

1708 

1709 .. versionadded:: 1.17 

1710 

1711 Returns 

1712 ------- 

1713 grid : one ndarray or tuple of ndarrays 

1714 If sparse is False: 

1715 Returns one array of grid indices, 

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

1717 If sparse is True: 

1718 Returns a tuple of arrays, with 

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

1720 dimensions[i] in the ith place 

1721 

1722 See Also 

1723 -------- 

1724 mgrid, ogrid, meshgrid 

1725 

1726 Notes 

1727 ----- 

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

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

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

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

1732 

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

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

1735 

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

1737 

1738 Examples 

1739 -------- 

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

1741 >>> grid.shape 

1742 (2, 2, 3) 

1743 >>> grid[0] # row indices 

1744 array([[0, 0, 0], 

1745 [1, 1, 1]]) 

1746 >>> grid[1] # column indices 

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

1748 [0, 1, 2]]) 

1749 

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

1751 

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

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

1754 >>> x[row, col] 

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

1756 [4, 5, 6]]) 

1757 

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

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

1760 

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

1762 representation. 

1763 

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

1765 >>> i.shape 

1766 (2, 1) 

1767 >>> j.shape 

1768 (1, 3) 

1769 >>> i # row indices 

1770 array([[0], 

1771 [1]]) 

1772 >>> j # column indices 

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

1774 

1775 """ 

1776 dimensions = tuple(dimensions) 

1777 N = len(dimensions) 

1778 shape = (1,)*N 

1779 if sparse: 

1780 res = tuple() 

1781 else: 

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

1783 for i, dim in enumerate(dimensions): 

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

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

1786 ) 

1787 if sparse: 

1788 res = res + (idx,) 

1789 else: 

1790 res[i] = idx 

1791 return res 

1792 

1793 

1794def _fromfunction_dispatcher(function, shape, *, dtype=None, like=None, **kwargs): 

1795 return (like,) 

1796 

1797 

1798@set_array_function_like_doc 

1799@set_module('numpy') 

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

1801 """ 

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

1803 

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

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

1806 

1807 Parameters 

1808 ---------- 

1809 function : callable 

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

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

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

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

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

1815 shape : (N,) tuple of ints 

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

1817 the coordinate arrays passed to `function`. 

1818 dtype : data-type, optional 

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

1820 By default, `dtype` is float. 

1821 ${ARRAY_FUNCTION_LIKE} 

1822 

1823 .. versionadded:: 1.20.0 

1824 

1825 Returns 

1826 ------- 

1827 fromfunction : any 

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

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

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

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

1832 

1833 See Also 

1834 -------- 

1835 indices, meshgrid 

1836 

1837 Notes 

1838 ----- 

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

1840 

1841 Examples 

1842 -------- 

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

1844 array([[0., 0.], 

1845 [1., 1.]]) 

1846  

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

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

1849 [0., 1.]]) 

1850  

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

1852 array([[ True, False, False], 

1853 [False, True, False], 

1854 [False, False, True]]) 

1855 

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

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

1858 [1, 2, 3], 

1859 [2, 3, 4]]) 

1860 

1861 """ 

1862 if like is not None: 

1863 return _fromfunction_with_like(function, shape, dtype=dtype, like=like, **kwargs) 

1864 

1865 args = indices(shape, dtype=dtype) 

1866 return function(*args, **kwargs) 

1867 

1868 

1869_fromfunction_with_like = array_function_dispatch( 

1870 _fromfunction_dispatcher, use_like=True 

1871)(fromfunction) 

1872 

1873 

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

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

1876 

1877 

1878@set_module('numpy') 

1879def isscalar(element): 

1880 """ 

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

1882 

1883 Parameters 

1884 ---------- 

1885 element : any 

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

1887 

1888 Returns 

1889 ------- 

1890 val : bool 

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

1892 

1893 See Also 

1894 -------- 

1895 ndim : Get the number of dimensions of an array 

1896 

1897 Notes 

1898 ----- 

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

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

1901 non-numerical elements such as strings. 

1902 

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

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

1905 functions in the style of the ``dx`` arguments to `gradient` and the ``bins`` 

1906 argument to `histogram`. Some key differences: 

1907 

1908 +--------------------------------------+---------------+-------------------+ 

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

1910 +======================================+===============+===================+ 

1911 | PEP 3141 numeric objects (including | ``True`` | ``True`` | 

1912 | builtins) | | | 

1913 +--------------------------------------+---------------+-------------------+ 

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

1915 +--------------------------------------+---------------+-------------------+ 

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

1917 | `pathlib.Path`, `Exception`, | | | 

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

1919 +--------------------------------------+---------------+-------------------+ 

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

1921 | `matplotlib.figure.Figure` | | | 

1922 +--------------------------------------+---------------+-------------------+ 

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

1924 +--------------------------------------+---------------+-------------------+ 

1925 | other numpy arrays | ``False`` | ``False`` | 

1926 +--------------------------------------+---------------+-------------------+ 

1927 | `list`, `tuple`, and other sequence | ``False`` | ``False`` | 

1928 | objects | | | 

1929 +--------------------------------------+---------------+-------------------+ 

1930 

1931 Examples 

1932 -------- 

1933 >>> np.isscalar(3.1) 

1934 True 

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

1936 False 

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

1938 False 

1939 >>> np.isscalar(False) 

1940 True 

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

1942 True 

1943 

1944 NumPy supports PEP 3141 numbers: 

1945 

1946 >>> from fractions import Fraction 

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

1948 True 

1949 >>> from numbers import Number 

1950 >>> np.isscalar(Number()) 

1951 True 

1952 

1953 """ 

1954 return (isinstance(element, generic) 

1955 or type(element) in ScalarType 

1956 or isinstance(element, numbers.Number)) 

1957 

1958 

1959@set_module('numpy') 

1960def binary_repr(num, width=None): 

1961 """ 

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

1963 

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

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

1966 returned, with respect to that width. 

1967 

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

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

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

1971 system can represent every integer in the range 

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

1973 

1974 Parameters 

1975 ---------- 

1976 num : int 

1977 Only an integer decimal number can be used. 

1978 width : int, optional 

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

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

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

1982 designated form. 

1983 

1984 If the `width` value is insufficient, it will be ignored, and `num` will 

1985 be returned in binary (`num` > 0) or two's complement (`num` < 0) form 

1986 with its width equal to the minimum number of bits needed to represent 

1987 the number in the designated form. This behavior is deprecated and will 

1988 later raise an error. 

1989 

1990 .. deprecated:: 1.12.0 

1991 

1992 Returns 

1993 ------- 

1994 bin : str 

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

1996 

1997 See Also 

1998 -------- 

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

2000 system. 

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

2002 

2003 Notes 

2004 ----- 

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

2006 faster. 

2007 

2008 References 

2009 ---------- 

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

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

2012 

2013 Examples 

2014 -------- 

2015 >>> np.binary_repr(3) 

2016 '11' 

2017 >>> np.binary_repr(-3) 

2018 '-11' 

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

2020 '0011' 

2021 

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

2023 width is specified: 

2024 

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

2026 '101' 

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

2028 '11101' 

2029 

2030 """ 

2031 def warn_if_insufficient(width, binwidth): 

2032 if width is not None and width < binwidth: 

2033 warnings.warn( 

2034 "Insufficient bit width provided. This behavior " 

2035 "will raise an error in the future.", DeprecationWarning, 

2036 stacklevel=3) 

2037 

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

2039 # casts to floating point. 

2040 num = operator.index(num) 

2041 

2042 if num == 0: 

2043 return '0' * (width or 1) 

2044 

2045 elif num > 0: 

2046 binary = bin(num)[2:] 

2047 binwidth = len(binary) 

2048 outwidth = (binwidth if width is None 

2049 else max(binwidth, width)) 

2050 warn_if_insufficient(width, binwidth) 

2051 return binary.zfill(outwidth) 

2052 

2053 else: 

2054 if width is None: 

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

2056 

2057 else: 

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

2059 

2060 # See gh-8679: remove extra digit 

2061 # for numbers at boundaries. 

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

2063 poswidth -= 1 

2064 

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

2066 binary = bin(twocomp)[2:] 

2067 binwidth = len(binary) 

2068 

2069 outwidth = max(binwidth, width) 

2070 warn_if_insufficient(width, binwidth) 

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

2072 

2073 

2074@set_module('numpy') 

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

2076 """ 

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

2078 

2079 Parameters 

2080 ---------- 

2081 number : int 

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

2083 base : int, optional 

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

2085 the default value is 2. 

2086 padding : int, optional 

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

2088 

2089 Returns 

2090 ------- 

2091 out : str 

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

2093 

2094 See Also 

2095 -------- 

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

2097 

2098 Examples 

2099 -------- 

2100 >>> np.base_repr(5) 

2101 '101' 

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

2103 '11' 

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

2105 '00012' 

2106 

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

2108 'A' 

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

2110 '20' 

2111 

2112 """ 

2113 digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' 

2114 if base > len(digits): 

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

2116 elif base < 2: 

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

2118 

2119 num = abs(number) 

2120 res = [] 

2121 while num: 

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

2123 num //= base 

2124 if padding: 

2125 res.append('0' * padding) 

2126 if number < 0: 

2127 res.append('-') 

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

2129 

2130 

2131# These are all essentially abbreviations 

2132# These might wind up in a special abbreviations module 

2133 

2134 

2135def _maketup(descr, val): 

2136 dt = dtype(descr) 

2137 # Place val in all scalar tuples: 

2138 fields = dt.fields 

2139 if fields is None: 

2140 return val 

2141 else: 

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

2143 return tuple(res) 

2144 

2145 

2146def _identity_dispatcher(n, dtype=None, *, like=None): 

2147 return (like,) 

2148 

2149 

2150@set_array_function_like_doc 

2151@set_module('numpy') 

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

2153 """ 

2154 Return the identity array. 

2155 

2156 The identity array is a square array with ones on 

2157 the main diagonal. 

2158 

2159 Parameters 

2160 ---------- 

2161 n : int 

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

2163 dtype : data-type, optional 

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

2165 ${ARRAY_FUNCTION_LIKE} 

2166 

2167 .. versionadded:: 1.20.0 

2168 

2169 Returns 

2170 ------- 

2171 out : ndarray 

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

2173 and all other elements 0. 

2174 

2175 Examples 

2176 -------- 

2177 >>> np.identity(3) 

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

2179 [0., 1., 0.], 

2180 [0., 0., 1.]]) 

2181 

2182 """ 

2183 if like is not None: 

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

2185 

2186 from numpy import eye 

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

2188 

2189 

2190_identity_with_like = array_function_dispatch( 

2191 _identity_dispatcher, use_like=True 

2192)(identity) 

2193 

2194 

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

2196 return (a, b) 

2197 

2198 

2199@array_function_dispatch(_allclose_dispatcher) 

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

2201 """ 

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

2203 

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

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

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

2207 between `a` and `b`. 

2208 

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

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

2211 place and of the same sign in both arrays. 

2212 

2213 Parameters 

2214 ---------- 

2215 a, b : array_like 

2216 Input arrays to compare. 

2217 rtol : float 

2218 The relative tolerance parameter (see Notes). 

2219 atol : float 

2220 The absolute tolerance parameter (see Notes). 

2221 equal_nan : bool 

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

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

2224 

2225 .. versionadded:: 1.10.0 

2226 

2227 Returns 

2228 ------- 

2229 allclose : bool 

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

2231 tolerance; False otherwise. 

2232 

2233 See Also 

2234 -------- 

2235 isclose, all, any, equal 

2236 

2237 Notes 

2238 ----- 

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

2240 True. 

2241 

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

2243 

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

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

2246 some rare cases. 

2247 

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

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

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

2251 `equal` but not `array_equal`. 

2252 

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

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

2255 

2256 Examples 

2257 -------- 

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

2259 False 

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

2261 True 

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

2263 False 

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

2265 False 

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

2267 True 

2268 

2269 """ 

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

2271 return bool(res) 

2272 

2273 

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

2275 return (a, b) 

2276 

2277 

2278@array_function_dispatch(_isclose_dispatcher) 

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

2280 """ 

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

2282 tolerance. 

2283 

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

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

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

2287 between `a` and `b`. 

2288 

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

2290 that are much smaller than one (see Notes). 

2291 

2292 Parameters 

2293 ---------- 

2294 a, b : array_like 

2295 Input arrays to compare. 

2296 rtol : float 

2297 The relative tolerance parameter (see Notes). 

2298 atol : float 

2299 The absolute tolerance parameter (see Notes). 

2300 equal_nan : bool 

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

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

2303 

2304 Returns 

2305 ------- 

2306 y : array_like 

2307 Returns a boolean array of where `a` and `b` are equal within the 

2308 given tolerance. If both `a` and `b` are scalars, returns a single 

2309 boolean value. 

2310 

2311 See Also 

2312 -------- 

2313 allclose 

2314 math.isclose 

2315 

2316 Notes 

2317 ----- 

2318 .. versionadded:: 1.7.0 

2319 

2320 For finite values, isclose uses the following equation to test whether 

2321 two floating point values are equivalent. 

2322 

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

2324 

2325 Unlike the built-in `math.isclose`, the above equation is not symmetric 

2326 in `a` and `b` -- it assumes `b` is the reference value -- so that 

2327 `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore, 

2328 the default value of atol is not zero, and is used to determine what 

2329 small values should be considered close to zero. The default value is 

2330 appropriate for expected values of order unity: if the expected values 

2331 are significantly smaller than one, it can result in false positives. 

2332 `atol` should be carefully selected for the use case at hand. A zero value 

2333 for `atol` will result in `False` if either `a` or `b` is zero. 

2334 

2335 `isclose` is not defined for non-numeric data types. 

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

2337 

2338 Examples 

2339 -------- 

2340 >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8]) 

2341 array([ True, False]) 

2342 >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9]) 

2343 array([ True, True]) 

2344 >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9]) 

2345 array([False, True]) 

2346 >>> np.isclose([1.0, np.nan], [1.0, np.nan]) 

2347 array([ True, False]) 

2348 >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) 

2349 array([ True, True]) 

2350 >>> np.isclose([1e-8, 1e-7], [0.0, 0.0]) 

2351 array([ True, False]) 

2352 >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0) 

2353 array([False, False]) 

2354 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0]) 

2355 array([ True, True]) 

2356 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0) 

2357 array([False, True]) 

2358 """ 

2359 def within_tol(x, y, atol, rtol): 

2360 with errstate(invalid='ignore'), _no_nep50_warning(): 

2361 return less_equal(abs(x-y), atol + rtol * abs(y)) 

2362 

2363 x = asanyarray(a) 

2364 y = asanyarray(b) 

2365 

2366 # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT). 

2367 # This will cause casting of x later. Also, make sure to allow subclasses 

2368 # (e.g., for numpy.ma). 

2369 # NOTE: We explicitly allow timedelta, which used to work. This could 

2370 # possibly be deprecated. See also gh-18286. 

2371 # timedelta works if `atol` is an integer or also a timedelta. 

2372 # Although, the default tolerances are unlikely to be useful 

2373 if y.dtype.kind != "m": 

2374 dt = multiarray.result_type(y, 1.) 

2375 y = asanyarray(y, dtype=dt) 

2376 

2377 xfin = isfinite(x) 

2378 yfin = isfinite(y) 

2379 if all(xfin) and all(yfin): 

2380 return within_tol(x, y, atol, rtol) 

2381 else: 

2382 finite = xfin & yfin 

2383 cond = zeros_like(finite, subok=True) 

2384 # Because we're using boolean indexing, x & y must be the same shape. 

2385 # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in 

2386 # lib.stride_tricks, though, so we can't import it here. 

2387 x = x * ones_like(cond) 

2388 y = y * ones_like(cond) 

2389 # Avoid subtraction with infinite/nan values... 

2390 cond[finite] = within_tol(x[finite], y[finite], atol, rtol) 

2391 # Check for equality of infinite values... 

2392 cond[~finite] = (x[~finite] == y[~finite]) 

2393 if equal_nan: 

2394 # Make NaN == NaN 

2395 both_nan = isnan(x) & isnan(y) 

2396 

2397 # Needed to treat masked arrays correctly. = True would not work. 

2398 cond[both_nan] = both_nan[both_nan] 

2399 

2400 return cond[()] # Flatten 0d arrays to scalars 

2401 

2402 

2403def _array_equal_dispatcher(a1, a2, equal_nan=None): 

2404 return (a1, a2) 

2405 

2406 

2407@array_function_dispatch(_array_equal_dispatcher) 

2408def array_equal(a1, a2, equal_nan=False): 

2409 """ 

2410 True if two arrays have the same shape and elements, False otherwise. 

2411 

2412 Parameters 

2413 ---------- 

2414 a1, a2 : array_like 

2415 Input arrays. 

2416 equal_nan : bool 

2417 Whether to compare NaN's as equal. If the dtype of a1 and a2 is 

2418 complex, values will be considered equal if either the real or the 

2419 imaginary component of a given value is ``nan``. 

2420 

2421 .. versionadded:: 1.19.0 

2422 

2423 Returns 

2424 ------- 

2425 b : bool 

2426 Returns True if the arrays are equal. 

2427 

2428 See Also 

2429 -------- 

2430 allclose: Returns True if two arrays are element-wise equal within a 

2431 tolerance. 

2432 array_equiv: Returns True if input arrays are shape consistent and all 

2433 elements equal. 

2434 

2435 Examples 

2436 -------- 

2437 >>> np.array_equal([1, 2], [1, 2]) 

2438 True 

2439 >>> np.array_equal(np.array([1, 2]), np.array([1, 2])) 

2440 True 

2441 >>> np.array_equal([1, 2], [1, 2, 3]) 

2442 False 

2443 >>> np.array_equal([1, 2], [1, 4]) 

2444 False 

2445 >>> a = np.array([1, np.nan]) 

2446 >>> np.array_equal(a, a) 

2447 False 

2448 >>> np.array_equal(a, a, equal_nan=True) 

2449 True 

2450 

2451 When ``equal_nan`` is True, complex values with nan components are 

2452 considered equal if either the real *or* the imaginary components are nan. 

2453 

2454 >>> a = np.array([1 + 1j]) 

2455 >>> b = a.copy() 

2456 >>> a.real = np.nan 

2457 >>> b.imag = np.nan 

2458 >>> np.array_equal(a, b, equal_nan=True) 

2459 True 

2460 """ 

2461 try: 

2462 a1, a2 = asarray(a1), asarray(a2) 

2463 except Exception: 

2464 return False 

2465 if a1.shape != a2.shape: 

2466 return False 

2467 if not equal_nan: 

2468 return bool(asarray(a1 == a2).all()) 

2469 # Handling NaN values if equal_nan is True 

2470 a1nan, a2nan = isnan(a1), isnan(a2) 

2471 # NaN's occur at different locations 

2472 if not (a1nan == a2nan).all(): 

2473 return False 

2474 # Shapes of a1, a2 and masks are guaranteed to be consistent by this point 

2475 return bool(asarray(a1[~a1nan] == a2[~a1nan]).all()) 

2476 

2477 

2478def _array_equiv_dispatcher(a1, a2): 

2479 return (a1, a2) 

2480 

2481 

2482@array_function_dispatch(_array_equiv_dispatcher) 

2483def array_equiv(a1, a2): 

2484 """ 

2485 Returns True if input arrays are shape consistent and all elements equal. 

2486 

2487 Shape consistent means they are either the same shape, or one input array 

2488 can be broadcasted to create the same shape as the other one. 

2489 

2490 Parameters 

2491 ---------- 

2492 a1, a2 : array_like 

2493 Input arrays. 

2494 

2495 Returns 

2496 ------- 

2497 out : bool 

2498 True if equivalent, False otherwise. 

2499 

2500 Examples 

2501 -------- 

2502 >>> np.array_equiv([1, 2], [1, 2]) 

2503 True 

2504 >>> np.array_equiv([1, 2], [1, 3]) 

2505 False 

2506 

2507 Showing the shape equivalence: 

2508 

2509 >>> np.array_equiv([1, 2], [[1, 2], [1, 2]]) 

2510 True 

2511 >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]]) 

2512 False 

2513 

2514 >>> np.array_equiv([1, 2], [[1, 2], [1, 3]]) 

2515 False 

2516 

2517 """ 

2518 try: 

2519 a1, a2 = asarray(a1), asarray(a2) 

2520 except Exception: 

2521 return False 

2522 try: 

2523 multiarray.broadcast(a1, a2) 

2524 except Exception: 

2525 return False 

2526 

2527 return bool(asarray(a1 == a2).all()) 

2528 

2529 

2530Inf = inf = infty = Infinity = PINF 

2531nan = NaN = NAN 

2532False_ = bool_(False) 

2533True_ = bool_(True) 

2534 

2535 

2536def extend_all(module): 

2537 existing = set(__all__) 

2538 mall = getattr(module, '__all__') 

2539 for a in mall: 

2540 if a not in existing: 

2541 __all__.append(a) 

2542 

2543 

2544from .umath import * 

2545from .numerictypes import * 

2546from . import fromnumeric 

2547from .fromnumeric import * 

2548from . import arrayprint 

2549from .arrayprint import * 

2550from . import _asarray 

2551from ._asarray import * 

2552from . import _ufunc_config 

2553from ._ufunc_config import * 

2554extend_all(fromnumeric) 

2555extend_all(umath) 

2556extend_all(numerictypes) 

2557extend_all(arrayprint) 

2558extend_all(_asarray) 

2559extend_all(_ufunc_config)