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

104 statements  

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

1""" 

2Create the numpy._core.multiarray namespace for backward compatibility.  

3In v1.16 the multiarray and umath c-extension modules were merged into  

4a single _multiarray_umath extension module. So we replicate the old  

5namespace by importing from the extension module. 

6 

7""" 

8 

9import functools 

10from . import overrides 

11from . import _multiarray_umath 

12from ._multiarray_umath import * # noqa: F403 

13# These imports are needed for backward compatibility, 

14# do not change them. issue gh-15518 

15# _get_ndarray_c_version is semi-public, on purpose not added to __all__ 

16from ._multiarray_umath import ( 

17 _flagdict, from_dlpack, _place, _reconstruct, 

18 _vec_string, _ARRAY_API, _monotonicity, _get_ndarray_c_version, 

19 _get_madvise_hugepage, _set_madvise_hugepage, 

20 _get_promotion_state, _set_promotion_state 

21 ) 

22 

23__all__ = [ 

24 '_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS', 

25 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS', 

26 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI', 

27 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP', 

28 '_flagdict', 'from_dlpack', '_place', '_reconstruct', '_vec_string', 

29 '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray', 

30 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount', 

31 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast', 

32 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2', 

33 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data', 

34 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype', 

35 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat', 

36 'frombuffer', 'fromfile', 'fromiter', 'fromstring', 

37 'get_handler_name', 'get_handler_version', 'inner', 'interp', 

38 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'may_share_memory', 

39 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters', 

40 'normalize_axis_index', 'packbits', 'promote_types', 'putmask', 

41 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function', 

42 'set_legacy_print_mode', 

43 'set_typeDict', 'shares_memory', 'typeinfo', 

44 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros', 

45 '_get_promotion_state', '_set_promotion_state'] 

46 

47# For backward compatibility, make sure pickle imports  

48# these functions from here 

49_reconstruct.__module__ = 'numpy._core.multiarray' 

50scalar.__module__ = 'numpy._core.multiarray' 

51 

52 

53from_dlpack.__module__ = 'numpy' 

54arange.__module__ = 'numpy' 

55array.__module__ = 'numpy' 

56asarray.__module__ = 'numpy' 

57asanyarray.__module__ = 'numpy' 

58ascontiguousarray.__module__ = 'numpy' 

59asfortranarray.__module__ = 'numpy' 

60datetime_data.__module__ = 'numpy' 

61empty.__module__ = 'numpy' 

62frombuffer.__module__ = 'numpy' 

63fromfile.__module__ = 'numpy' 

64fromiter.__module__ = 'numpy' 

65frompyfunc.__module__ = 'numpy' 

66fromstring.__module__ = 'numpy' 

67may_share_memory.__module__ = 'numpy' 

68nested_iters.__module__ = 'numpy' 

69promote_types.__module__ = 'numpy' 

70zeros.__module__ = 'numpy' 

71_get_promotion_state.__module__ = 'numpy' 

72_set_promotion_state.__module__ = 'numpy' 

73normalize_axis_index.__module__ = 'numpy.lib.array_utils' 

74 

75 

76# We can't verify dispatcher signatures because NumPy's C functions don't 

77# support introspection. 

78array_function_from_c_func_and_dispatcher = functools.partial( 

79 overrides.array_function_from_dispatcher, 

80 module='numpy', docs_from_dispatcher=True, verify=False) 

81 

82 

83@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like) 

84def empty_like( 

85 prototype, dtype=None, order=None, subok=None, shape=None, *, device=None 

86): 

87 """ 

88 empty_like(prototype, dtype=None, order='K', subok=True, shape=None, *, 

89 device=None) 

90 

91 Return a new array with the same shape and type as a given array. 

92 

93 Parameters 

94 ---------- 

95 prototype : array_like 

96 The shape and data-type of `prototype` define these same attributes 

97 of the returned array. 

98 dtype : data-type, optional 

99 Overrides the data type of the result. 

100 

101 .. versionadded:: 1.6.0 

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

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

104 'F' means F-order, 'A' means 'F' if `prototype` is Fortran 

105 contiguous, 'C' otherwise. 'K' means match the layout of `prototype` 

106 as closely as possible. 

107 

108 .. versionadded:: 1.6.0 

109 subok : bool, optional. 

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

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

112 to True. 

113 shape : int or sequence of ints, optional. 

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

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

116 order='C' is implied. 

117 

118 .. versionadded:: 1.17.0 

119 device : str, optional 

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

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

122 

123 .. versionadded:: 2.0.0 

124 

125 Returns 

126 ------- 

127 out : ndarray 

128 Array of uninitialized (arbitrary) data with the same 

129 shape and type as `prototype`. 

130 

131 See Also 

132 -------- 

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

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

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

136 empty : Return a new uninitialized array. 

137 

138 Notes 

139 ----- 

140 Unlike other array creation functions (e.g. `zeros_like`, `ones_like`, 

141 `full_like`), `empty_like` does not initialize the values of the array, 

142 and may therefore be marginally faster. However, the values stored in the 

143 newly allocated array are arbitrary. For reproducible behavior, be sure 

144 to set each element of the array before reading. 

145 

146 Examples 

147 -------- 

148 >>> a = ([1,2,3], [4,5,6]) # a is array-like 

149 >>> np.empty_like(a) 

150 array([[-1073741821, -1073741821, 3], # uninitialized 

151 [ 0, 0, -1073741821]]) 

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

153 >>> np.empty_like(a) 

154 array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninit 

155 [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]]) 

156 

157 """ 

158 return (prototype,) 

159 

160 

161@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate) 

162def concatenate(arrays, axis=None, out=None, *, dtype=None, casting=None): 

163 """ 

164 concatenate( 

165 (a1, a2, ...),  

166 axis=0,  

167 out=None,  

168 dtype=None,  

169 casting="same_kind" 

170 ) 

171 

172 Join a sequence of arrays along an existing axis. 

173 

174 Parameters 

175 ---------- 

176 a1, a2, ... : sequence of array_like 

177 The arrays must have the same shape, except in the dimension 

178 corresponding to `axis` (the first, by default). 

179 axis : int, optional 

180 The axis along which the arrays will be joined. If axis is None, 

181 arrays are flattened before use. Default is 0. 

182 out : ndarray, optional 

183 If provided, the destination to place the result. The shape must be 

184 correct, matching that of what concatenate would have returned if no 

185 out argument were specified. 

186 dtype : str or dtype 

187 If provided, the destination array will have this dtype. Cannot be 

188 provided together with `out`. 

189 

190 .. versionadded:: 1.20.0 

191 

192 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 

193 Controls what kind of data casting may occur. Defaults to 'same_kind'. 

194 For a description of the options, please see :term:`casting`. 

195  

196 .. versionadded:: 1.20.0 

197 

198 Returns 

199 ------- 

200 res : ndarray 

201 The concatenated array. 

202 

203 See Also 

204 -------- 

205 ma.concatenate : Concatenate function that preserves input masks. 

206 array_split : Split an array into multiple sub-arrays of equal or 

207 near-equal size. 

208 split : Split array into a list of multiple sub-arrays of equal size. 

209 hsplit : Split array into multiple sub-arrays horizontally (column wise). 

210 vsplit : Split array into multiple sub-arrays vertically (row wise). 

211 dsplit : Split array into multiple sub-arrays along the 3rd axis (depth). 

212 stack : Stack a sequence of arrays along a new axis. 

213 block : Assemble arrays from blocks. 

214 hstack : Stack arrays in sequence horizontally (column wise). 

215 vstack : Stack arrays in sequence vertically (row wise). 

216 dstack : Stack arrays in sequence depth wise (along third dimension). 

217 column_stack : Stack 1-D arrays as columns into a 2-D array. 

218 

219 Notes 

220 ----- 

221 When one or more of the arrays to be concatenated is a MaskedArray, 

222 this function will return a MaskedArray object instead of an ndarray, 

223 but the input masks are *not* preserved. In cases where a MaskedArray 

224 is expected as input, use the ma.concatenate function from the masked 

225 array module instead. 

226 

227 Examples 

228 -------- 

229 >>> a = np.array([[1, 2], [3, 4]]) 

230 >>> b = np.array([[5, 6]]) 

231 >>> np.concatenate((a, b), axis=0) 

232 array([[1, 2], 

233 [3, 4], 

234 [5, 6]]) 

235 >>> np.concatenate((a, b.T), axis=1) 

236 array([[1, 2, 5], 

237 [3, 4, 6]]) 

238 >>> np.concatenate((a, b), axis=None) 

239 array([1, 2, 3, 4, 5, 6]) 

240 

241 This function will not preserve masking of MaskedArray inputs. 

242 

243 >>> a = np.ma.arange(3) 

244 >>> a[1] = np.ma.masked 

245 >>> b = np.arange(2, 5) 

246 >>> a 

247 masked_array(data=[0, --, 2], 

248 mask=[False, True, False], 

249 fill_value=999999) 

250 >>> b 

251 array([2, 3, 4]) 

252 >>> np.concatenate([a, b]) 

253 masked_array(data=[0, 1, 2, 2, 3, 4], 

254 mask=False, 

255 fill_value=999999) 

256 >>> np.ma.concatenate([a, b]) 

257 masked_array(data=[0, --, 2, 2, 3, 4], 

258 mask=[False, True, False, False, False, False], 

259 fill_value=999999) 

260 

261 """ 

262 if out is not None: 

263 # optimize for the typical case where only arrays is provided 

264 arrays = list(arrays) 

265 arrays.append(out) 

266 return arrays 

267 

268 

269@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner) 

270def inner(a, b): 

271 """ 

272 inner(a, b, /) 

273 

274 Inner product of two arrays. 

275 

276 Ordinary inner product of vectors for 1-D arrays (without complex 

277 conjugation), in higher dimensions a sum product over the last axes. 

278 

279 Parameters 

280 ---------- 

281 a, b : array_like 

282 If `a` and `b` are nonscalar, their last dimensions must match. 

283 

284 Returns 

285 ------- 

286 out : ndarray 

287 If `a` and `b` are both 

288 scalars or both 1-D arrays then a scalar is returned; otherwise 

289 an array is returned. 

290 ``out.shape = (*a.shape[:-1], *b.shape[:-1])`` 

291 

292 Raises 

293 ------ 

294 ValueError 

295 If both `a` and `b` are nonscalar and their last dimensions have 

296 different sizes. 

297 

298 See Also 

299 -------- 

300 tensordot : Sum products over arbitrary axes. 

301 dot : Generalised matrix product, using second last dimension of `b`. 

302 einsum : Einstein summation convention. 

303 

304 Notes 

305 ----- 

306 For vectors (1-D arrays) it computes the ordinary inner-product:: 

307 

308 np.inner(a, b) = sum(a[:]*b[:]) 

309 

310 More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``:: 

311 

312 np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1)) 

313 

314 or explicitly:: 

315 

316 np.inner(a, b)[i0,...,ir-2,j0,...,js-2] 

317 = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:]) 

318 

319 In addition `a` or `b` may be scalars, in which case:: 

320 

321 np.inner(a,b) = a*b 

322 

323 Examples 

324 -------- 

325 Ordinary inner product for vectors: 

326 

327 >>> a = np.array([1,2,3]) 

328 >>> b = np.array([0,1,0]) 

329 >>> np.inner(a, b) 

330 2 

331 

332 Some multidimensional examples: 

333 

334 >>> a = np.arange(24).reshape((2,3,4)) 

335 >>> b = np.arange(4) 

336 >>> c = np.inner(a, b) 

337 >>> c.shape 

338 (2, 3) 

339 >>> c 

340 array([[ 14, 38, 62], 

341 [ 86, 110, 134]]) 

342 

343 >>> a = np.arange(2).reshape((1,1,2)) 

344 >>> b = np.arange(6).reshape((3,2)) 

345 >>> c = np.inner(a, b) 

346 >>> c.shape 

347 (1, 1, 3) 

348 >>> c 

349 array([[[1, 3, 5]]]) 

350 

351 An example where `b` is a scalar: 

352 

353 >>> np.inner(np.eye(2), 7) 

354 array([[7., 0.], 

355 [0., 7.]]) 

356 

357 """ 

358 return (a, b) 

359 

360 

361@array_function_from_c_func_and_dispatcher(_multiarray_umath.where) 

362def where(condition, x=None, y=None): 

363 """ 

364 where(condition, [x, y], /) 

365 

366 Return elements chosen from `x` or `y` depending on `condition`. 

367 

368 .. note:: 

369 When only `condition` is provided, this function is a shorthand for 

370 ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be 

371 preferred, as it behaves correctly for subclasses. The rest of this 

372 documentation covers only the case where all three arguments are 

373 provided. 

374 

375 Parameters 

376 ---------- 

377 condition : array_like, bool 

378 Where True, yield `x`, otherwise yield `y`. 

379 x, y : array_like 

380 Values from which to choose. `x`, `y` and `condition` need to be 

381 broadcastable to some shape. 

382 

383 Returns 

384 ------- 

385 out : ndarray 

386 An array with elements from `x` where `condition` is True, and elements 

387 from `y` elsewhere. 

388 

389 See Also 

390 -------- 

391 choose 

392 nonzero : The function that is called when x and y are omitted 

393 

394 Notes 

395 ----- 

396 If all the arrays are 1-D, `where` is equivalent to:: 

397 

398 [xv if c else yv 

399 for c, xv, yv in zip(condition, x, y)] 

400 

401 Examples 

402 -------- 

403 >>> a = np.arange(10) 

404 >>> a 

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

406 >>> np.where(a < 5, a, 10*a) 

407 array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90]) 

408 

409 This can be used on multidimensional arrays too: 

410 

411 >>> np.where([[True, False], [True, True]], 

412 ... [[1, 2], [3, 4]], 

413 ... [[9, 8], [7, 6]]) 

414 array([[1, 8], 

415 [3, 4]]) 

416 

417 The shapes of x, y, and the condition are broadcast together: 

418 

419 >>> x, y = np.ogrid[:3, :4] 

420 >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast 

421 array([[10, 0, 0, 0], 

422 [10, 11, 1, 1], 

423 [10, 11, 12, 2]]) 

424 

425 >>> a = np.array([[0, 1, 2], 

426 ... [0, 2, 4], 

427 ... [0, 3, 6]]) 

428 >>> np.where(a < 4, a, -1) # -1 is broadcast 

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

430 [ 0, 2, -1], 

431 [ 0, 3, -1]]) 

432 """ 

433 return (condition, x, y) 

434 

435 

436@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort) 

437def lexsort(keys, axis=None): 

438 """ 

439 lexsort(keys, axis=-1) 

440 

441 Perform an indirect stable sort using a sequence of keys. 

442 

443 Given multiple sorting keys, lexsort returns an array of integer indices 

444 that describes the sort order by multiple keys. The last key in the 

445 sequence is used for the primary sort order, ties are broken by the 

446 second-to-last key, and so on. 

447 

448 Parameters 

449 ---------- 

450 keys : (k, m, n, ...) array-like 

451 The `k` keys to be sorted. The *last* key (e.g, the last 

452 row if `keys` is a 2D array) is the primary sort key. 

453 Each element of `keys` along the zeroth axis must be 

454 an array-like object of the same shape. 

455 axis : int, optional 

456 Axis to be indirectly sorted. By default, sort over the last axis 

457 of each sequence. Separate slices along `axis` sorted over 

458 independently; see last example. 

459 

460 Returns 

461 ------- 

462 indices : (m, n, ...) ndarray of ints 

463 Array of indices that sort the keys along the specified axis. 

464 

465 See Also 

466 -------- 

467 argsort : Indirect sort. 

468 ndarray.sort : In-place sort. 

469 sort : Return a sorted copy of an array. 

470 

471 Examples 

472 -------- 

473 Sort names: first by surname, then by name. 

474 

475 >>> surnames = ('Hertz', 'Galilei', 'Hertz') 

476 >>> first_names = ('Heinrich', 'Galileo', 'Gustav') 

477 >>> ind = np.lexsort((first_names, surnames)) 

478 >>> ind 

479 array([1, 2, 0]) 

480 

481 >>> [surnames[i] + ", " + first_names[i] for i in ind] 

482 ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich'] 

483 

484 Sort according to two numerical keys, first by elements 

485 of ``a``, then breaking ties according to elements of ``b``: 

486 

487 >>> a = [1, 5, 1, 4, 3, 4, 4] # First sequence 

488 >>> b = [9, 4, 0, 4, 0, 2, 1] # Second sequence 

489 >>> ind = np.lexsort((b, a)) # Sort by `a`, then by `b` 

490 >>> ind 

491 array([2, 0, 4, 6, 5, 3, 1]) 

492 >>> [(a[i], b[i]) for i in ind] 

493 [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)] 

494 

495 Compare against `argsort`, which would sort each key independently. 

496 

497 >>> np.argsort((b, a), kind='stable') 

498 array([[2, 4, 6, 5, 1, 3, 0], 

499 [0, 2, 4, 3, 5, 6, 1]]) 

500 

501 To sort lexicographically with `argsort`, we would need to provide a 

502 structured array. 

503 

504 >>> x = np.array([(ai, bi) for ai, bi in zip(a, b)], 

505 ... dtype = np.dtype([('x', int), ('y', int)])) 

506 >>> np.argsort(x) # or np.argsort(x, order=('x', 'y')) 

507 array([2, 0, 4, 6, 5, 3, 1]) 

508 

509 The zeroth axis of `keys` always corresponds with the sequence of keys, 

510 so 2D arrays are treated just like other sequences of keys. 

511 

512 >>> arr = np.asarray([b, a]) 

513 >>> ind2 = np.lexsort(arr) 

514 >>> np.testing.assert_equal(ind2, ind) 

515 

516 Accordingly, the `axis` parameter refers to an axis of *each* key, not of 

517 the `keys` argument itself. For instance, the array ``arr`` is treated as 

518 a sequence of two 1-D keys, so specifying ``axis=0`` is equivalent to 

519 using the default axis, ``axis=-1``. 

520 

521 >>> np.testing.assert_equal(np.lexsort(arr, axis=0), 

522 ... np.lexsort(arr, axis=-1)) 

523 

524 For higher-dimensional arrays, the axis parameter begins to matter. The 

525 resulting array has the same shape as each key, and the values are what 

526 we would expect if `lexsort` were performed on corresponding slices 

527 of the keys independently. For instance, 

528 

529 >>> x = [[1, 2, 3, 4], 

530 ... [4, 3, 2, 1], 

531 ... [2, 1, 4, 3]] 

532 >>> y = [[2, 2, 1, 1], 

533 ... [1, 2, 1, 2], 

534 ... [1, 1, 2, 1]] 

535 >>> np.lexsort((x, y), axis=1) 

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

537 [2, 0, 3, 1], 

538 [1, 0, 3, 2]]) 

539 

540 Each row of the result is what we would expect if we were to perform 

541 `lexsort` on the corresponding row of the keys: 

542 

543 >>> for i in range(3): 

544 ... print(np.lexsort((x[i], y[i]))) 

545 [2 3 0 1] 

546 [2 0 3 1] 

547 [1 0 3 2] 

548 

549 """ 

550 if isinstance(keys, tuple): 

551 return keys 

552 else: 

553 return (keys,) 

554 

555 

556@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast) 

557def can_cast(from_, to, casting=None): 

558 """ 

559 can_cast(from_, to, casting='safe') 

560 

561 Returns True if cast between data types can occur according to the 

562 casting rule. 

563 

564 Parameters 

565 ---------- 

566 from_ : dtype, dtype specifier, NumPy scalar, or array 

567 Data type, NumPy scalar, or array to cast from. 

568 to : dtype or dtype specifier 

569 Data type to cast to. 

570 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 

571 Controls what kind of data casting may occur. 

572 

573 * 'no' means the data types should not be cast at all. 

574 * 'equiv' means only byte-order changes are allowed. 

575 * 'safe' means only casts which can preserve values are allowed. 

576 * 'same_kind' means only safe casts or casts within a kind, 

577 like float64 to float32, are allowed. 

578 * 'unsafe' means any data conversions may be done. 

579 

580 Returns 

581 ------- 

582 out : bool 

583 True if cast can occur according to the casting rule. 

584 

585 Notes 

586 ----- 

587 .. versionchanged:: 1.17.0 

588 Casting between a simple data type and a structured one is possible only 

589 for "unsafe" casting. Casting to multiple fields is allowed, but 

590 casting from multiple fields is not. 

591 

592 .. versionchanged:: 1.9.0 

593 Casting from numeric to string types in 'safe' casting mode requires 

594 that the string dtype length is long enough to store the maximum 

595 integer/float value converted. 

596 

597 .. versionchanged:: 2.0 

598 This function does not support Python scalars anymore and does not 

599 apply any value-based logic for 0-D arrays and NumPy scalars. 

600 

601 See also 

602 -------- 

603 dtype, result_type 

604 

605 Examples 

606 -------- 

607 Basic examples 

608 

609 >>> np.can_cast(np.int32, np.int64) 

610 True 

611 >>> np.can_cast(np.float64, complex) 

612 True 

613 >>> np.can_cast(complex, float) 

614 False 

615 

616 >>> np.can_cast('i8', 'f8') 

617 True 

618 >>> np.can_cast('i8', 'f4') 

619 False 

620 >>> np.can_cast('i4', 'S4') 

621 False 

622 

623 """ 

624 return (from_,) 

625 

626 

627@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type) 

628def min_scalar_type(a): 

629 """ 

630 min_scalar_type(a, /) 

631 

632 For scalar ``a``, returns the data type with the smallest size 

633 and smallest scalar kind which can hold its value. For non-scalar 

634 array ``a``, returns the vector's dtype unmodified. 

635 

636 Floating point values are not demoted to integers, 

637 and complex values are not demoted to floats. 

638 

639 Parameters 

640 ---------- 

641 a : scalar or array_like 

642 The value whose minimal data type is to be found. 

643 

644 Returns 

645 ------- 

646 out : dtype 

647 The minimal data type. 

648 

649 Notes 

650 ----- 

651 .. versionadded:: 1.6.0 

652 

653 See Also 

654 -------- 

655 result_type, promote_types, dtype, can_cast 

656 

657 Examples 

658 -------- 

659 >>> np.min_scalar_type(10) 

660 dtype('uint8') 

661 

662 >>> np.min_scalar_type(-260) 

663 dtype('int16') 

664 

665 >>> np.min_scalar_type(3.1) 

666 dtype('float16') 

667 

668 >>> np.min_scalar_type(1e50) 

669 dtype('float64') 

670 

671 >>> np.min_scalar_type(np.arange(4,dtype='f8')) 

672 dtype('float64') 

673 

674 """ 

675 return (a,) 

676 

677 

678@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type) 

679def result_type(*arrays_and_dtypes): 

680 """ 

681 result_type(*arrays_and_dtypes) 

682 

683 Returns the type that results from applying the NumPy 

684 type promotion rules to the arguments. 

685 

686 Type promotion in NumPy works similarly to the rules in languages 

687 like C++, with some slight differences. When both scalars and 

688 arrays are used, the array's type takes precedence and the actual value 

689 of the scalar is taken into account. 

690 

691 For example, calculating 3*a, where a is an array of 32-bit floats, 

692 intuitively should result in a 32-bit float output. If the 3 is a 

693 32-bit integer, the NumPy rules indicate it can't convert losslessly 

694 into a 32-bit float, so a 64-bit float should be the result type. 

695 By examining the value of the constant, '3', we see that it fits in 

696 an 8-bit integer, which can be cast losslessly into the 32-bit float. 

697 

698 Parameters 

699 ---------- 

700 arrays_and_dtypes : list of arrays and dtypes 

701 The operands of some operation whose result type is needed. 

702 

703 Returns 

704 ------- 

705 out : dtype 

706 The result type. 

707 

708 See also 

709 -------- 

710 dtype, promote_types, min_scalar_type, can_cast 

711 

712 Notes 

713 ----- 

714 .. versionadded:: 1.6.0 

715 

716 The specific algorithm used is as follows. 

717 

718 Categories are determined by first checking which of boolean, 

719 integer (int/uint), or floating point (float/complex) the maximum 

720 kind of all the arrays and the scalars are. 

721 

722 If there are only scalars or the maximum category of the scalars 

723 is higher than the maximum category of the arrays, 

724 the data types are combined with :func:`promote_types` 

725 to produce the return value. 

726 

727 Otherwise, `min_scalar_type` is called on each scalar, and 

728 the resulting data types are all combined with :func:`promote_types` 

729 to produce the return value. 

730 

731 The set of int values is not a subset of the uint values for types 

732 with the same number of bits, something not reflected in 

733 :func:`min_scalar_type`, but handled as a special case in `result_type`. 

734 

735 Examples 

736 -------- 

737 >>> np.result_type(3, np.arange(7, dtype='i1')) 

738 dtype('int8') 

739 

740 >>> np.result_type('i4', 'c8') 

741 dtype('complex128') 

742 

743 >>> np.result_type(3.0, -2) 

744 dtype('float64') 

745 

746 """ 

747 return arrays_and_dtypes 

748 

749 

750@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) 

751def dot(a, b, out=None): 

752 """ 

753 dot(a, b, out=None) 

754 

755 Dot product of two arrays. Specifically, 

756 

757 - If both `a` and `b` are 1-D arrays, it is inner product of vectors 

758 (without complex conjugation). 

759 

760 - If both `a` and `b` are 2-D arrays, it is matrix multiplication, 

761 but using :func:`matmul` or ``a @ b`` is preferred. 

762 

763 - If either `a` or `b` is 0-D (scalar), it is equivalent to 

764 :func:`multiply` and using ``numpy.multiply(a, b)`` or ``a * b`` is 

765 preferred. 

766 

767 - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over 

768 the last axis of `a` and `b`. 

769 

770 - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a 

771 sum product over the last axis of `a` and the second-to-last axis of 

772 `b`:: 

773 

774 dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) 

775 

776 It uses an optimized BLAS library when possible (see `numpy.linalg`). 

777 

778 Parameters 

779 ---------- 

780 a : array_like 

781 First argument. 

782 b : array_like 

783 Second argument. 

784 out : ndarray, optional 

785 Output argument. This must have the exact kind that would be returned 

786 if it was not used. In particular, it must have the right type, must be 

787 C-contiguous, and its dtype must be the dtype that would be returned 

788 for `dot(a,b)`. This is a performance feature. Therefore, if these 

789 conditions are not met, an exception is raised, instead of attempting 

790 to be flexible. 

791 

792 Returns 

793 ------- 

794 output : ndarray 

795 Returns the dot product of `a` and `b`. If `a` and `b` are both 

796 scalars or both 1-D arrays then a scalar is returned; otherwise 

797 an array is returned. 

798 If `out` is given, then it is returned. 

799 

800 Raises 

801 ------ 

802 ValueError 

803 If the last dimension of `a` is not the same size as 

804 the second-to-last dimension of `b`. 

805 

806 See Also 

807 -------- 

808 vdot : Complex-conjugating dot product. 

809 tensordot : Sum products over arbitrary axes. 

810 einsum : Einstein summation convention. 

811 matmul : '@' operator as method with out parameter. 

812 linalg.multi_dot : Chained dot product. 

813 

814 Examples 

815 -------- 

816 >>> np.dot(3, 4) 

817 12 

818 

819 Neither argument is complex-conjugated: 

820 

821 >>> np.dot([2j, 3j], [2j, 3j]) 

822 (-13+0j) 

823 

824 For 2-D arrays it is the matrix product: 

825 

826 >>> a = [[1, 0], [0, 1]] 

827 >>> b = [[4, 1], [2, 2]] 

828 >>> np.dot(a, b) 

829 array([[4, 1], 

830 [2, 2]]) 

831 

832 >>> a = np.arange(3*4*5*6).reshape((3,4,5,6)) 

833 >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3)) 

834 >>> np.dot(a, b)[2,3,2,1,2,2] 

835 499128 

836 >>> sum(a[2,3,2,:] * b[1,2,:,2]) 

837 499128 

838 

839 """ 

840 return (a, b, out) 

841 

842 

843@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot) 

844def vdot(a, b): 

845 """ 

846 vdot(a, b, /) 

847 

848 Return the dot product of two vectors. 

849 

850 The vdot(`a`, `b`) function handles complex numbers differently than 

851 dot(`a`, `b`). If the first argument is complex the complex conjugate 

852 of the first argument is used for the calculation of the dot product. 

853 

854 Note that `vdot` handles multidimensional arrays differently than `dot`: 

855 it does *not* perform a matrix product, but flattens input arguments 

856 to 1-D vectors first. Consequently, it should only be used for vectors. 

857 

858 Parameters 

859 ---------- 

860 a : array_like 

861 If `a` is complex the complex conjugate is taken before calculation 

862 of the dot product. 

863 b : array_like 

864 Second argument to the dot product. 

865 

866 Returns 

867 ------- 

868 output : ndarray 

869 Dot product of `a` and `b`. Can be an int, float, or 

870 complex depending on the types of `a` and `b`. 

871 

872 See Also 

873 -------- 

874 dot : Return the dot product without using the complex conjugate of the 

875 first argument. 

876 

877 Examples 

878 -------- 

879 >>> a = np.array([1+2j,3+4j]) 

880 >>> b = np.array([5+6j,7+8j]) 

881 >>> np.vdot(a, b) 

882 (70-8j) 

883 >>> np.vdot(b, a) 

884 (70+8j) 

885 

886 Note that higher-dimensional arrays are flattened! 

887 

888 >>> a = np.array([[1, 4], [5, 6]]) 

889 >>> b = np.array([[4, 1], [2, 2]]) 

890 >>> np.vdot(a, b) 

891 30 

892 >>> np.vdot(b, a) 

893 30 

894 >>> 1*4 + 4*1 + 5*2 + 6*2 

895 30 

896 

897 """ 

898 return (a, b) 

899 

900 

901@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount) 

902def bincount(x, weights=None, minlength=None): 

903 """ 

904 bincount(x, /, weights=None, minlength=0) 

905 

906 Count number of occurrences of each value in array of non-negative ints. 

907 

908 The number of bins (of size 1) is one larger than the largest value in 

909 `x`. If `minlength` is specified, there will be at least this number 

910 of bins in the output array (though it will be longer if necessary, 

911 depending on the contents of `x`). 

912 Each bin gives the number of occurrences of its index value in `x`. 

913 If `weights` is specified the input array is weighted by it, i.e. if a 

914 value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead 

915 of ``out[n] += 1``. 

916 

917 Parameters 

918 ---------- 

919 x : array_like, 1 dimension, nonnegative ints 

920 Input array. 

921 weights : array_like, optional 

922 Weights, array of the same shape as `x`. 

923 minlength : int, optional 

924 A minimum number of bins for the output array. 

925 

926 .. versionadded:: 1.6.0 

927 

928 Returns 

929 ------- 

930 out : ndarray of ints 

931 The result of binning the input array. 

932 The length of `out` is equal to ``np.amax(x)+1``. 

933 

934 Raises 

935 ------ 

936 ValueError 

937 If the input is not 1-dimensional, or contains elements with negative 

938 values, or if `minlength` is negative. 

939 TypeError 

940 If the type of the input is float or complex. 

941 

942 See Also 

943 -------- 

944 histogram, digitize, unique 

945 

946 Examples 

947 -------- 

948 >>> np.bincount(np.arange(5)) 

949 array([1, 1, 1, 1, 1]) 

950 >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) 

951 array([1, 3, 1, 1, 0, 0, 0, 1]) 

952 

953 >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23]) 

954 >>> np.bincount(x).size == np.amax(x)+1 

955 True 

956 

957 The input array needs to be of integer dtype, otherwise a 

958 TypeError is raised: 

959 

960 >>> np.bincount(np.arange(5, dtype=float)) 

961 Traceback (most recent call last): 

962 ... 

963 TypeError: Cannot cast array data from dtype('float64') to dtype('int64') 

964 according to the rule 'safe' 

965 

966 A possible use of ``bincount`` is to perform sums over 

967 variable-size chunks of an array, using the ``weights`` keyword. 

968 

969 >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights 

970 >>> x = np.array([0, 1, 1, 2, 2, 2]) 

971 >>> np.bincount(x, weights=w) 

972 array([ 0.3, 0.7, 1.1]) 

973 

974 """ 

975 return (x, weights) 

976 

977 

978@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index) 

979def ravel_multi_index(multi_index, dims, mode=None, order=None): 

980 """ 

981 ravel_multi_index(multi_index, dims, mode='raise', order='C') 

982 

983 Converts a tuple of index arrays into an array of flat 

984 indices, applying boundary modes to the multi-index. 

985 

986 Parameters 

987 ---------- 

988 multi_index : tuple of array_like 

989 A tuple of integer arrays, one array for each dimension. 

990 dims : tuple of ints 

991 The shape of array into which the indices from ``multi_index`` apply. 

992 mode : {'raise', 'wrap', 'clip'}, optional 

993 Specifies how out-of-bounds indices are handled. Can specify 

994 either one mode or a tuple of modes, one mode per index. 

995 

996 * 'raise' -- raise an error (default) 

997 * 'wrap' -- wrap around 

998 * 'clip' -- clip to the range 

999 

1000 In 'clip' mode, a negative index which would normally 

1001 wrap will clip to 0 instead. 

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

1003 Determines whether the multi-index should be viewed as 

1004 indexing in row-major (C-style) or column-major 

1005 (Fortran-style) order. 

1006 

1007 Returns 

1008 ------- 

1009 raveled_indices : ndarray 

1010 An array of indices into the flattened version of an array 

1011 of dimensions ``dims``. 

1012 

1013 See Also 

1014 -------- 

1015 unravel_index 

1016 

1017 Notes 

1018 ----- 

1019 .. versionadded:: 1.6.0 

1020 

1021 Examples 

1022 -------- 

1023 >>> arr = np.array([[3,6,6],[4,5,1]]) 

1024 >>> np.ravel_multi_index(arr, (7,6)) 

1025 array([22, 41, 37]) 

1026 >>> np.ravel_multi_index(arr, (7,6), order='F') 

1027 array([31, 41, 13]) 

1028 >>> np.ravel_multi_index(arr, (4,6), mode='clip') 

1029 array([22, 23, 19]) 

1030 >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap')) 

1031 array([12, 13, 13]) 

1032 

1033 >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9)) 

1034 1621 

1035 """ 

1036 return multi_index 

1037 

1038 

1039@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index) 

1040def unravel_index(indices, shape=None, order=None): 

1041 """ 

1042 unravel_index(indices, shape, order='C') 

1043 

1044 Converts a flat index or array of flat indices into a tuple 

1045 of coordinate arrays. 

1046 

1047 Parameters 

1048 ---------- 

1049 indices : array_like 

1050 An integer array whose elements are indices into the flattened 

1051 version of an array of dimensions ``shape``. Before version 1.6.0, 

1052 this function accepted just one index value. 

1053 shape : tuple of ints 

1054 The shape of the array to use for unraveling ``indices``. 

1055 

1056 .. versionchanged:: 1.16.0 

1057 Renamed from ``dims`` to ``shape``. 

1058 

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

1060 Determines whether the indices should be viewed as indexing in 

1061 row-major (C-style) or column-major (Fortran-style) order. 

1062 

1063 .. versionadded:: 1.6.0 

1064 

1065 Returns 

1066 ------- 

1067 unraveled_coords : tuple of ndarray 

1068 Each array in the tuple has the same shape as the ``indices`` 

1069 array. 

1070 

1071 See Also 

1072 -------- 

1073 ravel_multi_index 

1074 

1075 Examples 

1076 -------- 

1077 >>> np.unravel_index([22, 41, 37], (7,6)) 

1078 (array([3, 6, 6]), array([4, 5, 1])) 

1079 >>> np.unravel_index([31, 41, 13], (7,6), order='F') 

1080 (array([3, 6, 6]), array([4, 5, 1])) 

1081 

1082 >>> np.unravel_index(1621, (6,7,8,9)) 

1083 (3, 1, 4, 1) 

1084 

1085 """ 

1086 return (indices,) 

1087 

1088 

1089@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto) 

1090def copyto(dst, src, casting=None, where=None): 

1091 """ 

1092 copyto(dst, src, casting='same_kind', where=True) 

1093 

1094 Copies values from one array to another, broadcasting as necessary. 

1095 

1096 Raises a TypeError if the `casting` rule is violated, and if 

1097 `where` is provided, it selects which elements to copy. 

1098 

1099 .. versionadded:: 1.7.0 

1100 

1101 Parameters 

1102 ---------- 

1103 dst : ndarray 

1104 The array into which values are copied. 

1105 src : array_like 

1106 The array from which values are copied. 

1107 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional 

1108 Controls what kind of data casting may occur when copying. 

1109 

1110 * 'no' means the data types should not be cast at all. 

1111 * 'equiv' means only byte-order changes are allowed. 

1112 * 'safe' means only casts which can preserve values are allowed. 

1113 * 'same_kind' means only safe casts or casts within a kind, 

1114 like float64 to float32, are allowed. 

1115 * 'unsafe' means any data conversions may be done. 

1116 where : array_like of bool, optional 

1117 A boolean array which is broadcasted to match the dimensions 

1118 of `dst`, and selects elements to copy from `src` to `dst` 

1119 wherever it contains the value True. 

1120 

1121 Examples 

1122 -------- 

1123 >>> A = np.array([4, 5, 6]) 

1124 >>> B = [1, 2, 3] 

1125 >>> np.copyto(A, B) 

1126 >>> A 

1127 array([1, 2, 3]) 

1128 

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

1130 >>> B = [[4, 5, 6], [7, 8, 9]] 

1131 >>> np.copyto(A, B) 

1132 >>> A 

1133 array([[4, 5, 6], 

1134 [7, 8, 9]]) 

1135 

1136 """ 

1137 return (dst, src, where) 

1138 

1139 

1140@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask) 

1141def putmask(a, /, mask, values): 

1142 """ 

1143 putmask(a, mask, values) 

1144 

1145 Changes elements of an array based on conditional and input values. 

1146 

1147 Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``. 

1148 

1149 If `values` is not the same size as `a` and `mask` then it will repeat. 

1150 This gives behavior different from ``a[mask] = values``. 

1151 

1152 Parameters 

1153 ---------- 

1154 a : ndarray 

1155 Target array. 

1156 mask : array_like 

1157 Boolean mask array. It has to be the same shape as `a`. 

1158 values : array_like 

1159 Values to put into `a` where `mask` is True. If `values` is smaller 

1160 than `a` it will be repeated. 

1161 

1162 See Also 

1163 -------- 

1164 place, put, take, copyto 

1165 

1166 Examples 

1167 -------- 

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

1169 >>> np.putmask(x, x>2, x**2) 

1170 >>> x 

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

1172 [ 9, 16, 25]]) 

1173 

1174 If `values` is smaller than `a` it is repeated: 

1175 

1176 >>> x = np.arange(5) 

1177 >>> np.putmask(x, x>1, [-33, -44]) 

1178 >>> x 

1179 array([ 0, 1, -33, -44, -33]) 

1180 

1181 """ 

1182 return (a, mask, values) 

1183 

1184 

1185@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits) 

1186def packbits(a, axis=None, bitorder='big'): 

1187 """ 

1188 packbits(a, /, axis=None, bitorder='big') 

1189 

1190 Packs the elements of a binary-valued array into bits in a uint8 array. 

1191 

1192 The result is padded to full bytes by inserting zero bits at the end. 

1193 

1194 Parameters 

1195 ---------- 

1196 a : array_like 

1197 An array of integers or booleans whose elements should be packed to 

1198 bits. 

1199 axis : int, optional 

1200 The dimension over which bit-packing is done. 

1201 ``None`` implies packing the flattened array. 

1202 bitorder : {'big', 'little'}, optional 

1203 The order of the input bits. 'big' will mimic bin(val), 

1204 ``[0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011``, 'little' will 

1205 reverse the order so ``[1, 1, 0, 0, 0, 0, 0, 0] => 3``. 

1206 Defaults to 'big'. 

1207 

1208 .. versionadded:: 1.17.0 

1209 

1210 Returns 

1211 ------- 

1212 packed : ndarray 

1213 Array of type uint8 whose elements represent bits corresponding to the 

1214 logical (0 or nonzero) value of the input elements. The shape of 

1215 `packed` has the same number of dimensions as the input (unless `axis` 

1216 is None, in which case the output is 1-D). 

1217 

1218 See Also 

1219 -------- 

1220 unpackbits: Unpacks elements of a uint8 array into a binary-valued output 

1221 array. 

1222 

1223 Examples 

1224 -------- 

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

1226 ... [0,1,0]], 

1227 ... [[1,1,0], 

1228 ... [0,0,1]]]) 

1229 >>> b = np.packbits(a, axis=-1) 

1230 >>> b 

1231 array([[[160], 

1232 [ 64]], 

1233 [[192], 

1234 [ 32]]], dtype=uint8) 

1235 

1236 Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000, 

1237 and 32 = 0010 0000. 

1238 

1239 """ 

1240 return (a,) 

1241 

1242 

1243@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits) 

1244def unpackbits(a, axis=None, count=None, bitorder='big'): 

1245 """ 

1246 unpackbits(a, /, axis=None, count=None, bitorder='big') 

1247 

1248 Unpacks elements of a uint8 array into a binary-valued output array. 

1249 

1250 Each element of `a` represents a bit-field that should be unpacked 

1251 into a binary-valued output array. The shape of the output array is 

1252 either 1-D (if `axis` is ``None``) or the same shape as the input 

1253 array with unpacking done along the axis specified. 

1254 

1255 Parameters 

1256 ---------- 

1257 a : ndarray, uint8 type 

1258 Input array. 

1259 axis : int, optional 

1260 The dimension over which bit-unpacking is done. 

1261 ``None`` implies unpacking the flattened array. 

1262 count : int or None, optional 

1263 The number of elements to unpack along `axis`, provided as a way 

1264 of undoing the effect of packing a size that is not a multiple 

1265 of eight. A non-negative number means to only unpack `count` 

1266 bits. A negative number means to trim off that many bits from 

1267 the end. ``None`` means to unpack the entire array (the 

1268 default). Counts larger than the available number of bits will 

1269 add zero padding to the output. Negative counts must not 

1270 exceed the available number of bits. 

1271 

1272 .. versionadded:: 1.17.0 

1273 

1274 bitorder : {'big', 'little'}, optional 

1275 The order of the returned bits. 'big' will mimic bin(val), 

1276 ``3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1]``, 'little' will reverse 

1277 the order to ``[1, 1, 0, 0, 0, 0, 0, 0]``. 

1278 Defaults to 'big'. 

1279 

1280 .. versionadded:: 1.17.0 

1281 

1282 Returns 

1283 ------- 

1284 unpacked : ndarray, uint8 type 

1285 The elements are binary-valued (0 or 1). 

1286 

1287 See Also 

1288 -------- 

1289 packbits : Packs the elements of a binary-valued array into bits in 

1290 a uint8 array. 

1291 

1292 Examples 

1293 -------- 

1294 >>> a = np.array([[2], [7], [23]], dtype=np.uint8) 

1295 >>> a 

1296 array([[ 2], 

1297 [ 7], 

1298 [23]], dtype=uint8) 

1299 >>> b = np.unpackbits(a, axis=1) 

1300 >>> b 

1301 array([[0, 0, 0, 0, 0, 0, 1, 0], 

1302 [0, 0, 0, 0, 0, 1, 1, 1], 

1303 [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8) 

1304 >>> c = np.unpackbits(a, axis=1, count=-3) 

1305 >>> c 

1306 array([[0, 0, 0, 0, 0], 

1307 [0, 0, 0, 0, 0], 

1308 [0, 0, 0, 1, 0]], dtype=uint8) 

1309 

1310 >>> p = np.packbits(b, axis=0) 

1311 >>> np.unpackbits(p, axis=0) 

1312 array([[0, 0, 0, 0, 0, 0, 1, 0], 

1313 [0, 0, 0, 0, 0, 1, 1, 1], 

1314 [0, 0, 0, 1, 0, 1, 1, 1], 

1315 [0, 0, 0, 0, 0, 0, 0, 0], 

1316 [0, 0, 0, 0, 0, 0, 0, 0], 

1317 [0, 0, 0, 0, 0, 0, 0, 0], 

1318 [0, 0, 0, 0, 0, 0, 0, 0], 

1319 [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) 

1320 >>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0])) 

1321 True 

1322 

1323 """ 

1324 return (a,) 

1325 

1326 

1327@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory) 

1328def shares_memory(a, b, max_work=None): 

1329 """ 

1330 shares_memory(a, b, /, max_work=None) 

1331 

1332 Determine if two arrays share memory. 

1333 

1334 .. warning:: 

1335 

1336 This function can be exponentially slow for some inputs, unless 

1337 `max_work` is set to a finite number or ``MAY_SHARE_BOUNDS``. 

1338 If in doubt, use `numpy.may_share_memory` instead. 

1339 

1340 Parameters 

1341 ---------- 

1342 a, b : ndarray 

1343 Input arrays 

1344 max_work : int, optional 

1345 Effort to spend on solving the overlap problem (maximum number 

1346 of candidate solutions to consider). The following special 

1347 values are recognized: 

1348 

1349 max_work=MAY_SHARE_EXACT (default) 

1350 The problem is solved exactly. In this case, the function returns 

1351 True only if there is an element shared between the arrays. Finding 

1352 the exact solution may take extremely long in some cases. 

1353 max_work=MAY_SHARE_BOUNDS 

1354 Only the memory bounds of a and b are checked. 

1355 

1356 Raises 

1357 ------ 

1358 numpy.exceptions.TooHardError 

1359 Exceeded max_work. 

1360 

1361 Returns 

1362 ------- 

1363 out : bool 

1364 

1365 See Also 

1366 -------- 

1367 may_share_memory 

1368 

1369 Examples 

1370 -------- 

1371 >>> x = np.array([1, 2, 3, 4]) 

1372 >>> np.shares_memory(x, np.array([5, 6, 7])) 

1373 False 

1374 >>> np.shares_memory(x[::2], x) 

1375 True 

1376 >>> np.shares_memory(x[::2], x[1::2]) 

1377 False 

1378 

1379 Checking whether two arrays share memory is NP-complete, and 

1380 runtime may increase exponentially in the number of 

1381 dimensions. Hence, `max_work` should generally be set to a finite 

1382 number, as it is possible to construct examples that take 

1383 extremely long to run: 

1384 

1385 >>> from numpy.lib.stride_tricks import as_strided 

1386 >>> x = np.zeros([192163377], dtype=np.int8) 

1387 >>> x1 = as_strided( 

1388 ... x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049)) 

1389 >>> x2 = as_strided( 

1390 ... x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1)) 

1391 >>> np.shares_memory(x1, x2, max_work=1000) 

1392 Traceback (most recent call last): 

1393 ... 

1394 numpy.exceptions.TooHardError: Exceeded max_work 

1395 

1396 Running ``np.shares_memory(x1, x2)`` without `max_work` set takes 

1397 around 1 minute for this case. It is possible to find problems 

1398 that take still significantly longer. 

1399 

1400 """ 

1401 return (a, b) 

1402 

1403 

1404@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory) 

1405def may_share_memory(a, b, max_work=None): 

1406 """ 

1407 may_share_memory(a, b, /, max_work=None) 

1408 

1409 Determine if two arrays might share memory 

1410 

1411 A return of True does not necessarily mean that the two arrays 

1412 share any element. It just means that they *might*. 

1413 

1414 Only the memory bounds of a and b are checked by default. 

1415 

1416 Parameters 

1417 ---------- 

1418 a, b : ndarray 

1419 Input arrays 

1420 max_work : int, optional 

1421 Effort to spend on solving the overlap problem. See 

1422 `shares_memory` for details. Default for ``may_share_memory`` 

1423 is to do a bounds check. 

1424 

1425 Returns 

1426 ------- 

1427 out : bool 

1428 

1429 See Also 

1430 -------- 

1431 shares_memory 

1432 

1433 Examples 

1434 -------- 

1435 >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9])) 

1436 False 

1437 >>> x = np.zeros([3, 4]) 

1438 >>> np.may_share_memory(x[:,0], x[:,1]) 

1439 True 

1440 

1441 """ 

1442 return (a, b) 

1443 

1444 

1445@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday) 

1446def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None): 

1447 """ 

1448 is_busday( 

1449 dates,  

1450 weekmask='1111100',  

1451 holidays=None,  

1452 busdaycal=None,  

1453 out=None 

1454 ) 

1455 

1456 Calculates which of the given dates are valid days, and which are not. 

1457 

1458 .. versionadded:: 1.7.0 

1459 

1460 Parameters 

1461 ---------- 

1462 dates : array_like of datetime64[D] 

1463 The array of dates to process. 

1464 weekmask : str or array_like of bool, optional 

1465 A seven-element array indicating which of Monday through Sunday are 

1466 valid days. May be specified as a length-seven list or array, like 

1467 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string 

1468 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for 

1469 weekdays, optionally separated by white space. Valid abbreviations 

1470 are: Mon Tue Wed Thu Fri Sat Sun 

1471 holidays : array_like of datetime64[D], optional 

1472 An array of dates to consider as invalid dates. They may be 

1473 specified in any order, and NaT (not-a-time) dates are ignored. 

1474 This list is saved in a normalized form that is suited for 

1475 fast calculations of valid days. 

1476 busdaycal : busdaycalendar, optional 

1477 A `busdaycalendar` object which specifies the valid days. If this 

1478 parameter is provided, neither weekmask nor holidays may be 

1479 provided. 

1480 out : array of bool, optional 

1481 If provided, this array is filled with the result. 

1482 

1483 Returns 

1484 ------- 

1485 out : array of bool 

1486 An array with the same shape as ``dates``, containing True for 

1487 each valid day, and False for each invalid day. 

1488 

1489 See Also 

1490 -------- 

1491 busdaycalendar : An object that specifies a custom set of valid days. 

1492 busday_offset : Applies an offset counted in valid days. 

1493 busday_count : Counts how many valid days are in a half-open date range. 

1494 

1495 Examples 

1496 -------- 

1497 >>> # The weekdays are Friday, Saturday, and Monday 

1498 ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'], 

1499 ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) 

1500 array([False, False, True]) 

1501 """ 

1502 return (dates, weekmask, holidays, out) 

1503 

1504 

1505@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset) 

1506def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None, 

1507 busdaycal=None, out=None): 

1508 """ 

1509 busday_offset( 

1510 dates,  

1511 offsets,  

1512 roll='raise',  

1513 weekmask='1111100',  

1514 holidays=None,  

1515 busdaycal=None,  

1516 out=None 

1517 ) 

1518 

1519 First adjusts the date to fall on a valid day according to 

1520 the ``roll`` rule, then applies offsets to the given dates 

1521 counted in valid days. 

1522 

1523 .. versionadded:: 1.7.0 

1524 

1525 Parameters 

1526 ---------- 

1527 dates : array_like of datetime64[D] 

1528 The array of dates to process. 

1529 offsets : array_like of int 

1530 The array of offsets, which is broadcast with ``dates``. 

1531 roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', \ 

1532 'modifiedfollowing', 'modifiedpreceding'}, optional 

1533 How to treat dates that do not fall on a valid day. The default 

1534 is 'raise'. 

1535 

1536 * 'raise' means to raise an exception for an invalid day. 

1537 * 'nat' means to return a NaT (not-a-time) for an invalid day. 

1538 * 'forward' and 'following' mean to take the first valid day 

1539 later in time. 

1540 * 'backward' and 'preceding' mean to take the first valid day 

1541 earlier in time. 

1542 * 'modifiedfollowing' means to take the first valid day 

1543 later in time unless it is across a Month boundary, in which 

1544 case to take the first valid day earlier in time. 

1545 * 'modifiedpreceding' means to take the first valid day 

1546 earlier in time unless it is across a Month boundary, in which 

1547 case to take the first valid day later in time. 

1548 weekmask : str or array_like of bool, optional 

1549 A seven-element array indicating which of Monday through Sunday are 

1550 valid days. May be specified as a length-seven list or array, like 

1551 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string 

1552 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for 

1553 weekdays, optionally separated by white space. Valid abbreviations 

1554 are: Mon Tue Wed Thu Fri Sat Sun 

1555 holidays : array_like of datetime64[D], optional 

1556 An array of dates to consider as invalid dates. They may be 

1557 specified in any order, and NaT (not-a-time) dates are ignored. 

1558 This list is saved in a normalized form that is suited for 

1559 fast calculations of valid days. 

1560 busdaycal : busdaycalendar, optional 

1561 A `busdaycalendar` object which specifies the valid days. If this 

1562 parameter is provided, neither weekmask nor holidays may be 

1563 provided. 

1564 out : array of datetime64[D], optional 

1565 If provided, this array is filled with the result. 

1566 

1567 Returns 

1568 ------- 

1569 out : array of datetime64[D] 

1570 An array with a shape from broadcasting ``dates`` and ``offsets`` 

1571 together, containing the dates with offsets applied. 

1572 

1573 See Also 

1574 -------- 

1575 busdaycalendar : An object that specifies a custom set of valid days. 

1576 is_busday : Returns a boolean array indicating valid days. 

1577 busday_count : Counts how many valid days are in a half-open date range. 

1578 

1579 Examples 

1580 -------- 

1581 >>> # First business day in October 2011 (not accounting for holidays) 

1582 ... np.busday_offset('2011-10', 0, roll='forward') 

1583 numpy.datetime64('2011-10-03') 

1584 >>> # Last business day in February 2012 (not accounting for holidays) 

1585 ... np.busday_offset('2012-03', -1, roll='forward') 

1586 numpy.datetime64('2012-02-29') 

1587 >>> # Third Wednesday in January 2011 

1588 ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed') 

1589 numpy.datetime64('2011-01-19') 

1590 >>> # 2012 Mother's Day in Canada and the U.S. 

1591 ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun') 

1592 numpy.datetime64('2012-05-13') 

1593 

1594 >>> # First business day on or after a date 

1595 ... np.busday_offset('2011-03-20', 0, roll='forward') 

1596 numpy.datetime64('2011-03-21') 

1597 >>> np.busday_offset('2011-03-22', 0, roll='forward') 

1598 numpy.datetime64('2011-03-22') 

1599 >>> # First business day after a date 

1600 ... np.busday_offset('2011-03-20', 1, roll='backward') 

1601 numpy.datetime64('2011-03-21') 

1602 >>> np.busday_offset('2011-03-22', 1, roll='backward') 

1603 numpy.datetime64('2011-03-23') 

1604 """ 

1605 return (dates, offsets, weekmask, holidays, out) 

1606 

1607 

1608@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count) 

1609def busday_count(begindates, enddates, weekmask=None, holidays=None, 

1610 busdaycal=None, out=None): 

1611 """ 

1612 busday_count( 

1613 begindates,  

1614 enddates,  

1615 weekmask='1111100',  

1616 holidays=[],  

1617 busdaycal=None,  

1618 out=None 

1619 ) 

1620 

1621 Counts the number of valid days between `begindates` and 

1622 `enddates`, not including the day of `enddates`. 

1623 

1624 If ``enddates`` specifies a date value that is earlier than the 

1625 corresponding ``begindates`` date value, the count will be negative. 

1626 

1627 .. versionadded:: 1.7.0 

1628 

1629 Parameters 

1630 ---------- 

1631 begindates : array_like of datetime64[D] 

1632 The array of the first dates for counting. 

1633 enddates : array_like of datetime64[D] 

1634 The array of the end dates for counting, which are excluded 

1635 from the count themselves. 

1636 weekmask : str or array_like of bool, optional 

1637 A seven-element array indicating which of Monday through Sunday are 

1638 valid days. May be specified as a length-seven list or array, like 

1639 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string 

1640 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for 

1641 weekdays, optionally separated by white space. Valid abbreviations 

1642 are: Mon Tue Wed Thu Fri Sat Sun 

1643 holidays : array_like of datetime64[D], optional 

1644 An array of dates to consider as invalid dates. They may be 

1645 specified in any order, and NaT (not-a-time) dates are ignored. 

1646 This list is saved in a normalized form that is suited for 

1647 fast calculations of valid days. 

1648 busdaycal : busdaycalendar, optional 

1649 A `busdaycalendar` object which specifies the valid days. If this 

1650 parameter is provided, neither weekmask nor holidays may be 

1651 provided. 

1652 out : array of int, optional 

1653 If provided, this array is filled with the result. 

1654 

1655 Returns 

1656 ------- 

1657 out : array of int 

1658 An array with a shape from broadcasting ``begindates`` and ``enddates`` 

1659 together, containing the number of valid days between 

1660 the begin and end dates. 

1661 

1662 See Also 

1663 -------- 

1664 busdaycalendar : An object that specifies a custom set of valid days. 

1665 is_busday : Returns a boolean array indicating valid days. 

1666 busday_offset : Applies an offset counted in valid days. 

1667 

1668 Examples 

1669 -------- 

1670 >>> # Number of weekdays in January 2011 

1671 ... np.busday_count('2011-01', '2011-02') 

1672 21 

1673 >>> # Number of weekdays in 2011 

1674 >>> np.busday_count('2011', '2012') 

1675 260 

1676 >>> # Number of Saturdays in 2011 

1677 ... np.busday_count('2011', '2012', weekmask='Sat') 

1678 53 

1679 """ 

1680 return (begindates, enddates, weekmask, holidays, out) 

1681 

1682 

1683@array_function_from_c_func_and_dispatcher( 

1684 _multiarray_umath.datetime_as_string) 

1685def datetime_as_string(arr, unit=None, timezone=None, casting=None): 

1686 """ 

1687 datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind') 

1688 

1689 Convert an array of datetimes into an array of strings. 

1690 

1691 Parameters 

1692 ---------- 

1693 arr : array_like of datetime64 

1694 The array of UTC timestamps to format. 

1695 unit : str 

1696 One of None, 'auto', or  

1697 a :ref:`datetime unit <arrays.dtypes.dateunits>`. 

1698 timezone : {'naive', 'UTC', 'local'} or tzinfo 

1699 Timezone information to use when displaying the datetime. If 'UTC', 

1700 end with a Z to indicate UTC time. If 'local', convert to the local 

1701 timezone first, and suffix with a +-#### timezone offset. If a tzinfo 

1702 object, then do as with 'local', but use the specified timezone. 

1703 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'} 

1704 Casting to allow when changing between datetime units. 

1705 

1706 Returns 

1707 ------- 

1708 str_arr : ndarray 

1709 An array of strings the same shape as `arr`. 

1710 

1711 Examples 

1712 -------- 

1713 >>> import pytz 

1714 >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]') 

1715 >>> d 

1716 array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30', 

1717 '2002-10-27T07:30'], dtype='datetime64[m]') 

1718 

1719 Setting the timezone to UTC shows the same information, but with a Z suffix 

1720 

1721 >>> np.datetime_as_string(d, timezone='UTC') 

1722 array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z', 

1723 '2002-10-27T07:30Z'], dtype='<U35') 

1724 

1725 Note that we picked datetimes that cross a DST boundary. Passing in a 

1726 ``pytz`` timezone object will print the appropriate offset 

1727 

1728 >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern')) 

1729 array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400', 

1730 '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39') 

1731 

1732 Passing in a unit will change the precision 

1733 

1734 >>> np.datetime_as_string(d, unit='h') 

1735 array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'], 

1736 dtype='<U32') 

1737 >>> np.datetime_as_string(d, unit='s') 

1738 array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00', 

1739 '2002-10-27T07:30:00'], dtype='<U38') 

1740 

1741 'casting' can be used to specify whether precision can be changed 

1742 

1743 >>> np.datetime_as_string(d, unit='h', casting='safe') 

1744 Traceback (most recent call last): 

1745 ... 

1746 TypeError: Cannot create a datetime string as units 'h' from a NumPy 

1747 datetime with units 'm' according to the rule 'safe' 

1748 """ 

1749 return (arr,)