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 )
21
22__all__ = [
23 '_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS',
24 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS',
25 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI',
26 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP',
27 '_flagdict', 'from_dlpack', '_place', '_reconstruct', '_vec_string',
28 '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray',
29 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount',
30 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast',
31 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2',
32 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data',
33 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype',
34 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat',
35 'frombuffer', 'fromfile', 'fromiter', 'fromstring',
36 'get_handler_name', 'get_handler_version', 'inner', 'interp',
37 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'vecdot',
38 'may_share_memory', 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters',
39 'normalize_axis_index', 'packbits', 'promote_types', 'putmask',
40 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function',
41 'set_typeDict', 'shares_memory', 'typeinfo',
42 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros']
43
44# For backward compatibility, make sure pickle imports
45# these functions from here
46_reconstruct.__module__ = 'numpy._core.multiarray'
47scalar.__module__ = 'numpy._core.multiarray'
48
49
50from_dlpack.__module__ = 'numpy'
51arange.__module__ = 'numpy'
52array.__module__ = 'numpy'
53asarray.__module__ = 'numpy'
54asanyarray.__module__ = 'numpy'
55ascontiguousarray.__module__ = 'numpy'
56asfortranarray.__module__ = 'numpy'
57datetime_data.__module__ = 'numpy'
58empty.__module__ = 'numpy'
59frombuffer.__module__ = 'numpy'
60fromfile.__module__ = 'numpy'
61fromiter.__module__ = 'numpy'
62frompyfunc.__module__ = 'numpy'
63fromstring.__module__ = 'numpy'
64may_share_memory.__module__ = 'numpy'
65nested_iters.__module__ = 'numpy'
66promote_types.__module__ = 'numpy'
67zeros.__module__ = 'numpy'
68normalize_axis_index.__module__ = 'numpy.lib.array_utils'
69add_docstring.__module__ = 'numpy.lib'
70compare_chararrays.__module__ = 'numpy.char'
71
72
73def _override___module__():
74 namespace_names = globals()
75 for ufunc_name in [
76 'absolute', 'arccos', 'arccosh', 'add', 'arcsin', 'arcsinh', 'arctan',
77 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_count', 'invert',
78 'left_shift', 'bitwise_or', 'right_shift', 'bitwise_xor', 'cbrt',
79 'ceil', 'conjugate', 'copysign', 'cos', 'cosh', 'deg2rad', 'degrees',
80 'divide', 'divmod', 'equal', 'exp', 'exp2', 'expm1', 'fabs',
81 'float_power', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod',
82 'frexp', 'gcd', 'greater', 'greater_equal', 'heaviside', 'hypot',
83 'isfinite', 'isinf', 'isnan', 'isnat', 'lcm', 'ldexp', 'less',
84 'less_equal', 'log', 'log10', 'log1p', 'log2', 'logaddexp',
85 'logaddexp2', 'logical_and', 'logical_not', 'logical_or',
86 'logical_xor', 'matmul', 'matvec', 'maximum', 'minimum', 'remainder',
87 'modf', 'multiply', 'negative', 'nextafter', 'not_equal', 'positive',
88 'power', 'rad2deg', 'radians', 'reciprocal', 'rint', 'sign', 'signbit',
89 'sin', 'sinh', 'spacing', 'sqrt', 'square', 'subtract', 'tan', 'tanh',
90 'trunc', 'vecdot', 'vecmat',
91 ]:
92 ufunc = namespace_names[ufunc_name]
93 ufunc.__module__ = "numpy"
94 ufunc.__qualname__ = ufunc_name
95
96
97_override___module__()
98
99
100# We can't verify dispatcher signatures because NumPy's C functions don't
101# support introspection.
102array_function_from_c_func_and_dispatcher = functools.partial(
103 overrides.array_function_from_dispatcher,
104 module='numpy', docs_from_dispatcher=True, verify=False)
105
106
107@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like)
108def empty_like(
109 prototype, dtype=None, order=None, subok=None, shape=None, *, device=None
110):
111 """
112 empty_like(prototype, dtype=None, order='K', subok=True, shape=None, *,
113 device=None)
114
115 Return a new array with the same shape and type as a given array.
116
117 Parameters
118 ----------
119 prototype : array_like
120 The shape and data-type of `prototype` define these same attributes
121 of the returned array.
122 dtype : data-type, optional
123 Overrides the data type of the result.
124 order : {'C', 'F', 'A', or 'K'}, optional
125 Overrides the memory layout of the result. 'C' means C-order,
126 'F' means F-order, 'A' means 'F' if `prototype` is Fortran
127 contiguous, 'C' otherwise. 'K' means match the layout of `prototype`
128 as closely as possible.
129 subok : bool, optional.
130 If True, then the newly created array will use the sub-class
131 type of `prototype`, otherwise it will be a base-class array. Defaults
132 to True.
133 shape : int or sequence of ints, optional.
134 Overrides the shape of the result. If order='K' and the number of
135 dimensions is unchanged, will try to keep order, otherwise,
136 order='C' is implied.
137 device : str, optional
138 The device on which to place the created array. Default: None.
139 For Array-API interoperability only, so must be ``"cpu"`` if passed.
140
141 .. versionadded:: 2.0.0
142
143 Returns
144 -------
145 out : ndarray
146 Array of uninitialized (arbitrary) data with the same
147 shape and type as `prototype`.
148
149 See Also
150 --------
151 ones_like : Return an array of ones with shape and type of input.
152 zeros_like : Return an array of zeros with shape and type of input.
153 full_like : Return a new array with shape of input filled with value.
154 empty : Return a new uninitialized array.
155
156 Notes
157 -----
158 Unlike other array creation functions (e.g. `zeros_like`, `ones_like`,
159 `full_like`), `empty_like` does not initialize the values of the array,
160 and may therefore be marginally faster. However, the values stored in the
161 newly allocated array are arbitrary. For reproducible behavior, be sure
162 to set each element of the array before reading.
163
164 Examples
165 --------
166 >>> import numpy as np
167 >>> a = ([1,2,3], [4,5,6]) # a is array-like
168 >>> np.empty_like(a)
169 array([[-1073741821, -1073741821, 3], # uninitialized
170 [ 0, 0, -1073741821]])
171 >>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
172 >>> np.empty_like(a)
173 array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized
174 [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]])
175
176 """ # NOQA
177 return (prototype,)
178
179
180@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate)
181def concatenate(arrays, axis=None, out=None, *, dtype=None, casting=None):
182 """
183 concatenate(
184 (a1, a2, ...),
185 axis=0,
186 out=None,
187 dtype=None,
188 casting="same_kind"
189 )
190
191 Join a sequence of arrays along an existing axis.
192
193 Parameters
194 ----------
195 a1, a2, ... : sequence of array_like
196 The arrays must have the same shape, except in the dimension
197 corresponding to `axis` (the first, by default).
198 axis : int, optional
199 The axis along which the arrays will be joined. If axis is None,
200 arrays are flattened before use. Default is 0.
201 out : ndarray, optional
202 If provided, the destination to place the result. The shape must be
203 correct, matching that of what concatenate would have returned if no
204 out argument were specified.
205 dtype : str or dtype
206 If provided, the destination array will have this dtype. Cannot be
207 provided together with `out`.
208
209 .. versionadded:: 1.20.0
210
211 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
212 Controls what kind of data casting may occur. Defaults to 'same_kind'.
213 For a description of the options, please see :term:`casting`.
214
215 .. versionadded:: 1.20.0
216
217 Returns
218 -------
219 res : ndarray
220 The concatenated array.
221
222 See Also
223 --------
224 ma.concatenate : Concatenate function that preserves input masks.
225 array_split : Split an array into multiple sub-arrays of equal or
226 near-equal size.
227 split : Split array into a list of multiple sub-arrays of equal size.
228 hsplit : Split array into multiple sub-arrays horizontally (column wise).
229 vsplit : Split array into multiple sub-arrays vertically (row wise).
230 dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
231 stack : Stack a sequence of arrays along a new axis.
232 block : Assemble arrays from blocks.
233 hstack : Stack arrays in sequence horizontally (column wise).
234 vstack : Stack arrays in sequence vertically (row wise).
235 dstack : Stack arrays in sequence depth wise (along third dimension).
236 column_stack : Stack 1-D arrays as columns into a 2-D array.
237
238 Notes
239 -----
240 When one or more of the arrays to be concatenated is a MaskedArray,
241 this function will return a MaskedArray object instead of an ndarray,
242 but the input masks are *not* preserved. In cases where a MaskedArray
243 is expected as input, use the ma.concatenate function from the masked
244 array module instead.
245
246 Examples
247 --------
248 >>> import numpy as np
249 >>> a = np.array([[1, 2], [3, 4]])
250 >>> b = np.array([[5, 6]])
251 >>> np.concatenate((a, b), axis=0)
252 array([[1, 2],
253 [3, 4],
254 [5, 6]])
255 >>> np.concatenate((a, b.T), axis=1)
256 array([[1, 2, 5],
257 [3, 4, 6]])
258 >>> np.concatenate((a, b), axis=None)
259 array([1, 2, 3, 4, 5, 6])
260
261 This function will not preserve masking of MaskedArray inputs.
262
263 >>> a = np.ma.arange(3)
264 >>> a[1] = np.ma.masked
265 >>> b = np.arange(2, 5)
266 >>> a
267 masked_array(data=[0, --, 2],
268 mask=[False, True, False],
269 fill_value=999999)
270 >>> b
271 array([2, 3, 4])
272 >>> np.concatenate([a, b])
273 masked_array(data=[0, 1, 2, 2, 3, 4],
274 mask=False,
275 fill_value=999999)
276 >>> np.ma.concatenate([a, b])
277 masked_array(data=[0, --, 2, 2, 3, 4],
278 mask=[False, True, False, False, False, False],
279 fill_value=999999)
280
281 """
282 if out is not None:
283 # optimize for the typical case where only arrays is provided
284 arrays = list(arrays)
285 arrays.append(out)
286 return arrays
287
288
289@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner)
290def inner(a, b):
291 """
292 inner(a, b, /)
293
294 Inner product of two arrays.
295
296 Ordinary inner product of vectors for 1-D arrays (without complex
297 conjugation), in higher dimensions a sum product over the last axes.
298
299 Parameters
300 ----------
301 a, b : array_like
302 If `a` and `b` are nonscalar, their last dimensions must match.
303
304 Returns
305 -------
306 out : ndarray
307 If `a` and `b` are both
308 scalars or both 1-D arrays then a scalar is returned; otherwise
309 an array is returned.
310 ``out.shape = (*a.shape[:-1], *b.shape[:-1])``
311
312 Raises
313 ------
314 ValueError
315 If both `a` and `b` are nonscalar and their last dimensions have
316 different sizes.
317
318 See Also
319 --------
320 tensordot : Sum products over arbitrary axes.
321 dot : Generalised matrix product, using second last dimension of `b`.
322 vecdot : Vector dot product of two arrays.
323 einsum : Einstein summation convention.
324
325 Notes
326 -----
327 For vectors (1-D arrays) it computes the ordinary inner-product::
328
329 np.inner(a, b) = sum(a[:]*b[:])
330
331 More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``::
332
333 np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
334
335 or explicitly::
336
337 np.inner(a, b)[i0,...,ir-2,j0,...,js-2]
338 = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:])
339
340 In addition `a` or `b` may be scalars, in which case::
341
342 np.inner(a,b) = a*b
343
344 Examples
345 --------
346 Ordinary inner product for vectors:
347
348 >>> import numpy as np
349 >>> a = np.array([1,2,3])
350 >>> b = np.array([0,1,0])
351 >>> np.inner(a, b)
352 2
353
354 Some multidimensional examples:
355
356 >>> a = np.arange(24).reshape((2,3,4))
357 >>> b = np.arange(4)
358 >>> c = np.inner(a, b)
359 >>> c.shape
360 (2, 3)
361 >>> c
362 array([[ 14, 38, 62],
363 [ 86, 110, 134]])
364
365 >>> a = np.arange(2).reshape((1,1,2))
366 >>> b = np.arange(6).reshape((3,2))
367 >>> c = np.inner(a, b)
368 >>> c.shape
369 (1, 1, 3)
370 >>> c
371 array([[[1, 3, 5]]])
372
373 An example where `b` is a scalar:
374
375 >>> np.inner(np.eye(2), 7)
376 array([[7., 0.],
377 [0., 7.]])
378
379 """
380 return (a, b)
381
382
383@array_function_from_c_func_and_dispatcher(_multiarray_umath.where)
384def where(condition, x=None, y=None):
385 """
386 where(condition, [x, y], /)
387
388 Return elements chosen from `x` or `y` depending on `condition`.
389
390 .. note::
391 When only `condition` is provided, this function is a shorthand for
392 ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
393 preferred, as it behaves correctly for subclasses. The rest of this
394 documentation covers only the case where all three arguments are
395 provided.
396
397 Parameters
398 ----------
399 condition : array_like, bool
400 Where True, yield `x`, otherwise yield `y`.
401 x, y : array_like
402 Values from which to choose. `x`, `y` and `condition` need to be
403 broadcastable to some shape.
404
405 Returns
406 -------
407 out : ndarray
408 An array with elements from `x` where `condition` is True, and elements
409 from `y` elsewhere.
410
411 See Also
412 --------
413 choose
414 nonzero : The function that is called when x and y are omitted
415
416 Notes
417 -----
418 If all the arrays are 1-D, `where` is equivalent to::
419
420 [xv if c else yv
421 for c, xv, yv in zip(condition, x, y)]
422
423 Examples
424 --------
425 >>> import numpy as np
426 >>> a = np.arange(10)
427 >>> a
428 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
429 >>> np.where(a < 5, a, 10*a)
430 array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
431
432 This can be used on multidimensional arrays too:
433
434 >>> np.where([[True, False], [True, True]],
435 ... [[1, 2], [3, 4]],
436 ... [[9, 8], [7, 6]])
437 array([[1, 8],
438 [3, 4]])
439
440 The shapes of x, y, and the condition are broadcast together:
441
442 >>> x, y = np.ogrid[:3, :4]
443 >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast
444 array([[10, 0, 0, 0],
445 [10, 11, 1, 1],
446 [10, 11, 12, 2]])
447
448 >>> a = np.array([[0, 1, 2],
449 ... [0, 2, 4],
450 ... [0, 3, 6]])
451 >>> np.where(a < 4, a, -1) # -1 is broadcast
452 array([[ 0, 1, 2],
453 [ 0, 2, -1],
454 [ 0, 3, -1]])
455 """
456 return (condition, x, y)
457
458
459@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort)
460def lexsort(keys, axis=None):
461 """
462 lexsort(keys, axis=-1)
463
464 Perform an indirect stable sort using a sequence of keys.
465
466 Given multiple sorting keys, lexsort returns an array of integer indices
467 that describes the sort order by multiple keys. The last key in the
468 sequence is used for the primary sort order, ties are broken by the
469 second-to-last key, and so on.
470
471 Parameters
472 ----------
473 keys : (k, m, n, ...) array-like
474 The `k` keys to be sorted. The *last* key (e.g, the last
475 row if `keys` is a 2D array) is the primary sort key.
476 Each element of `keys` along the zeroth axis must be
477 an array-like object of the same shape.
478 axis : int, optional
479 Axis to be indirectly sorted. By default, sort over the last axis
480 of each sequence. Separate slices along `axis` sorted over
481 independently; see last example.
482
483 Returns
484 -------
485 indices : (m, n, ...) ndarray of ints
486 Array of indices that sort the keys along the specified axis.
487
488 See Also
489 --------
490 argsort : Indirect sort.
491 ndarray.sort : In-place sort.
492 sort : Return a sorted copy of an array.
493
494 Examples
495 --------
496 Sort names: first by surname, then by name.
497
498 >>> import numpy as np
499 >>> surnames = ('Hertz', 'Galilei', 'Hertz')
500 >>> first_names = ('Heinrich', 'Galileo', 'Gustav')
501 >>> ind = np.lexsort((first_names, surnames))
502 >>> ind
503 array([1, 2, 0])
504
505 >>> [surnames[i] + ", " + first_names[i] for i in ind]
506 ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
507
508 Sort according to two numerical keys, first by elements
509 of ``a``, then breaking ties according to elements of ``b``:
510
511 >>> a = [1, 5, 1, 4, 3, 4, 4] # First sequence
512 >>> b = [9, 4, 0, 4, 0, 2, 1] # Second sequence
513 >>> ind = np.lexsort((b, a)) # Sort by `a`, then by `b`
514 >>> ind
515 array([2, 0, 4, 6, 5, 3, 1])
516 >>> [(a[i], b[i]) for i in ind]
517 [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
518
519 Compare against `argsort`, which would sort each key independently.
520
521 >>> np.argsort((b, a), kind='stable')
522 array([[2, 4, 6, 5, 1, 3, 0],
523 [0, 2, 4, 3, 5, 6, 1]])
524
525 To sort lexicographically with `argsort`, we would need to provide a
526 structured array.
527
528 >>> x = np.array([(ai, bi) for ai, bi in zip(a, b)],
529 ... dtype = np.dtype([('x', int), ('y', int)]))
530 >>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
531 array([2, 0, 4, 6, 5, 3, 1])
532
533 The zeroth axis of `keys` always corresponds with the sequence of keys,
534 so 2D arrays are treated just like other sequences of keys.
535
536 >>> arr = np.asarray([b, a])
537 >>> ind2 = np.lexsort(arr)
538 >>> np.testing.assert_equal(ind2, ind)
539
540 Accordingly, the `axis` parameter refers to an axis of *each* key, not of
541 the `keys` argument itself. For instance, the array ``arr`` is treated as
542 a sequence of two 1-D keys, so specifying ``axis=0`` is equivalent to
543 using the default axis, ``axis=-1``.
544
545 >>> np.testing.assert_equal(np.lexsort(arr, axis=0),
546 ... np.lexsort(arr, axis=-1))
547
548 For higher-dimensional arrays, the axis parameter begins to matter. The
549 resulting array has the same shape as each key, and the values are what
550 we would expect if `lexsort` were performed on corresponding slices
551 of the keys independently. For instance,
552
553 >>> x = [[1, 2, 3, 4],
554 ... [4, 3, 2, 1],
555 ... [2, 1, 4, 3]]
556 >>> y = [[2, 2, 1, 1],
557 ... [1, 2, 1, 2],
558 ... [1, 1, 2, 1]]
559 >>> np.lexsort((x, y), axis=1)
560 array([[2, 3, 0, 1],
561 [2, 0, 3, 1],
562 [1, 0, 3, 2]])
563
564 Each row of the result is what we would expect if we were to perform
565 `lexsort` on the corresponding row of the keys:
566
567 >>> for i in range(3):
568 ... print(np.lexsort((x[i], y[i])))
569 [2 3 0 1]
570 [2 0 3 1]
571 [1 0 3 2]
572
573 """
574 if isinstance(keys, tuple):
575 return keys
576 else:
577 return (keys,)
578
579
580@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast)
581def can_cast(from_, to, casting=None):
582 """
583 can_cast(from_, to, casting='safe')
584
585 Returns True if cast between data types can occur according to the
586 casting rule.
587
588 Parameters
589 ----------
590 from_ : dtype, dtype specifier, NumPy scalar, or array
591 Data type, NumPy scalar, or array to cast from.
592 to : dtype or dtype specifier
593 Data type to cast to.
594 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
595 Controls what kind of data casting may occur.
596
597 * 'no' means the data types should not be cast at all.
598 * 'equiv' means only byte-order changes are allowed.
599 * 'safe' means only casts which can preserve values are allowed.
600 * 'same_kind' means only safe casts or casts within a kind,
601 like float64 to float32, are allowed.
602 * 'unsafe' means any data conversions may be done.
603
604 Returns
605 -------
606 out : bool
607 True if cast can occur according to the casting rule.
608
609 Notes
610 -----
611 .. versionchanged:: 2.0
612 This function does not support Python scalars anymore and does not
613 apply any value-based logic for 0-D arrays and NumPy scalars.
614
615 See also
616 --------
617 dtype, result_type
618
619 Examples
620 --------
621 Basic examples
622
623 >>> import numpy as np
624 >>> np.can_cast(np.int32, np.int64)
625 True
626 >>> np.can_cast(np.float64, complex)
627 True
628 >>> np.can_cast(complex, float)
629 False
630
631 >>> np.can_cast('i8', 'f8')
632 True
633 >>> np.can_cast('i8', 'f4')
634 False
635 >>> np.can_cast('i4', 'S4')
636 False
637
638 """
639 return (from_,)
640
641
642@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type)
643def min_scalar_type(a):
644 """
645 min_scalar_type(a, /)
646
647 For scalar ``a``, returns the data type with the smallest size
648 and smallest scalar kind which can hold its value. For non-scalar
649 array ``a``, returns the vector's dtype unmodified.
650
651 Floating point values are not demoted to integers,
652 and complex values are not demoted to floats.
653
654 Parameters
655 ----------
656 a : scalar or array_like
657 The value whose minimal data type is to be found.
658
659 Returns
660 -------
661 out : dtype
662 The minimal data type.
663
664 See Also
665 --------
666 result_type, promote_types, dtype, can_cast
667
668 Examples
669 --------
670 >>> import numpy as np
671 >>> np.min_scalar_type(10)
672 dtype('uint8')
673
674 >>> np.min_scalar_type(-260)
675 dtype('int16')
676
677 >>> np.min_scalar_type(3.1)
678 dtype('float16')
679
680 >>> np.min_scalar_type(1e50)
681 dtype('float64')
682
683 >>> np.min_scalar_type(np.arange(4,dtype='f8'))
684 dtype('float64')
685
686 """
687 return (a,)
688
689
690@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type)
691def result_type(*arrays_and_dtypes):
692 """
693 result_type(*arrays_and_dtypes)
694
695 Returns the type that results from applying the NumPy
696 type promotion rules to the arguments.
697
698 Type promotion in NumPy works similarly to the rules in languages
699 like C++, with some slight differences. When both scalars and
700 arrays are used, the array's type takes precedence and the actual value
701 of the scalar is taken into account.
702
703 For example, calculating 3*a, where a is an array of 32-bit floats,
704 intuitively should result in a 32-bit float output. If the 3 is a
705 32-bit integer, the NumPy rules indicate it can't convert losslessly
706 into a 32-bit float, so a 64-bit float should be the result type.
707 By examining the value of the constant, '3', we see that it fits in
708 an 8-bit integer, which can be cast losslessly into the 32-bit float.
709
710 Parameters
711 ----------
712 arrays_and_dtypes : list of arrays and dtypes
713 The operands of some operation whose result type is needed.
714
715 Returns
716 -------
717 out : dtype
718 The result type.
719
720 See also
721 --------
722 dtype, promote_types, min_scalar_type, can_cast
723
724 Notes
725 -----
726 The specific algorithm used is as follows.
727
728 Categories are determined by first checking which of boolean,
729 integer (int/uint), or floating point (float/complex) the maximum
730 kind of all the arrays and the scalars are.
731
732 If there are only scalars or the maximum category of the scalars
733 is higher than the maximum category of the arrays,
734 the data types are combined with :func:`promote_types`
735 to produce the return value.
736
737 Otherwise, `min_scalar_type` is called on each scalar, and
738 the resulting data types are all combined with :func:`promote_types`
739 to produce the return value.
740
741 The set of int values is not a subset of the uint values for types
742 with the same number of bits, something not reflected in
743 :func:`min_scalar_type`, but handled as a special case in `result_type`.
744
745 Examples
746 --------
747 >>> import numpy as np
748 >>> np.result_type(3, np.arange(7, dtype='i1'))
749 dtype('int8')
750
751 >>> np.result_type('i4', 'c8')
752 dtype('complex128')
753
754 >>> np.result_type(3.0, -2)
755 dtype('float64')
756
757 """
758 return arrays_and_dtypes
759
760
761@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot)
762def dot(a, b, out=None):
763 """
764 dot(a, b, out=None)
765
766 Dot product of two arrays. Specifically,
767
768 - If both `a` and `b` are 1-D arrays, it is inner product of vectors
769 (without complex conjugation).
770
771 - If both `a` and `b` are 2-D arrays, it is matrix multiplication,
772 but using :func:`matmul` or ``a @ b`` is preferred.
773
774 - If either `a` or `b` is 0-D (scalar), it is equivalent to
775 :func:`multiply` and using ``numpy.multiply(a, b)`` or ``a * b`` is
776 preferred.
777
778 - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
779 the last axis of `a` and `b`.
780
781 - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
782 sum product over the last axis of `a` and the second-to-last axis of
783 `b`::
784
785 dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
786
787 It uses an optimized BLAS library when possible (see `numpy.linalg`).
788
789 Parameters
790 ----------
791 a : array_like
792 First argument.
793 b : array_like
794 Second argument.
795 out : ndarray, optional
796 Output argument. This must have the exact kind that would be returned
797 if it was not used. In particular, it must have the right type, must be
798 C-contiguous, and its dtype must be the dtype that would be returned
799 for `dot(a,b)`. This is a performance feature. Therefore, if these
800 conditions are not met, an exception is raised, instead of attempting
801 to be flexible.
802
803 Returns
804 -------
805 output : ndarray
806 Returns the dot product of `a` and `b`. If `a` and `b` are both
807 scalars or both 1-D arrays then a scalar is returned; otherwise
808 an array is returned.
809 If `out` is given, then it is returned.
810
811 Raises
812 ------
813 ValueError
814 If the last dimension of `a` is not the same size as
815 the second-to-last dimension of `b`.
816
817 See Also
818 --------
819 vdot : Complex-conjugating dot product.
820 vecdot : Vector dot product of two arrays.
821 tensordot : Sum products over arbitrary axes.
822 einsum : Einstein summation convention.
823 matmul : '@' operator as method with out parameter.
824 linalg.multi_dot : Chained dot product.
825
826 Examples
827 --------
828 >>> import numpy as np
829 >>> np.dot(3, 4)
830 12
831
832 Neither argument is complex-conjugated:
833
834 >>> np.dot([2j, 3j], [2j, 3j])
835 (-13+0j)
836
837 For 2-D arrays it is the matrix product:
838
839 >>> a = [[1, 0], [0, 1]]
840 >>> b = [[4, 1], [2, 2]]
841 >>> np.dot(a, b)
842 array([[4, 1],
843 [2, 2]])
844
845 >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
846 >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
847 >>> np.dot(a, b)[2,3,2,1,2,2]
848 499128
849 >>> sum(a[2,3,2,:] * b[1,2,:,2])
850 499128
851
852 """
853 return (a, b, out)
854
855
856@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot)
857def vdot(a, b):
858 r"""
859 vdot(a, b, /)
860
861 Return the dot product of two vectors.
862
863 The `vdot` function handles complex numbers differently than `dot`:
864 if the first argument is complex, it is replaced by its complex conjugate
865 in the dot product calculation. `vdot` also handles multidimensional
866 arrays differently than `dot`: it does not perform a matrix product, but
867 flattens the arguments to 1-D arrays before taking a vector dot product.
868
869 Consequently, when the arguments are 2-D arrays of the same shape, this
870 function effectively returns their
871 `Frobenius inner product <https://en.wikipedia.org/wiki/Frobenius_inner_product>`_
872 (also known as the *trace inner product* or the *standard inner product*
873 on a vector space of matrices).
874
875 Parameters
876 ----------
877 a : array_like
878 If `a` is complex the complex conjugate is taken before calculation
879 of the dot product.
880 b : array_like
881 Second argument to the dot product.
882
883 Returns
884 -------
885 output : ndarray
886 Dot product of `a` and `b`. Can be an int, float, or
887 complex depending on the types of `a` and `b`.
888
889 See Also
890 --------
891 dot : Return the dot product without using the complex conjugate of the
892 first argument.
893
894 Examples
895 --------
896 >>> import numpy as np
897 >>> a = np.array([1+2j,3+4j])
898 >>> b = np.array([5+6j,7+8j])
899 >>> np.vdot(a, b)
900 (70-8j)
901 >>> np.vdot(b, a)
902 (70+8j)
903
904 Note that higher-dimensional arrays are flattened!
905
906 >>> a = np.array([[1, 4], [5, 6]])
907 >>> b = np.array([[4, 1], [2, 2]])
908 >>> np.vdot(a, b)
909 30
910 >>> np.vdot(b, a)
911 30
912 >>> 1*4 + 4*1 + 5*2 + 6*2
913 30
914
915 """ # noqa: E501
916 return (a, b)
917
918
919@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount)
920def bincount(x, weights=None, minlength=None):
921 """
922 bincount(x, /, weights=None, minlength=0)
923
924 Count number of occurrences of each value in array of non-negative ints.
925
926 The number of bins (of size 1) is one larger than the largest value in
927 `x`. If `minlength` is specified, there will be at least this number
928 of bins in the output array (though it will be longer if necessary,
929 depending on the contents of `x`).
930 Each bin gives the number of occurrences of its index value in `x`.
931 If `weights` is specified the input array is weighted by it, i.e. if a
932 value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead
933 of ``out[n] += 1``.
934
935 Parameters
936 ----------
937 x : array_like, 1 dimension, nonnegative ints
938 Input array.
939 weights : array_like, optional
940 Weights, array of the same shape as `x`.
941 minlength : int, optional
942 A minimum number of bins for the output array.
943
944 Returns
945 -------
946 out : ndarray of ints
947 The result of binning the input array.
948 The length of `out` is equal to ``np.amax(x)+1``.
949
950 Raises
951 ------
952 ValueError
953 If the input is not 1-dimensional, or contains elements with negative
954 values, or if `minlength` is negative.
955 TypeError
956 If the type of the input is float or complex.
957
958 See Also
959 --------
960 histogram, digitize, unique
961
962 Examples
963 --------
964 >>> import numpy as np
965 >>> np.bincount(np.arange(5))
966 array([1, 1, 1, 1, 1])
967 >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
968 array([1, 3, 1, 1, 0, 0, 0, 1])
969
970 >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
971 >>> np.bincount(x).size == np.amax(x)+1
972 True
973
974 The input array needs to be of integer dtype, otherwise a
975 TypeError is raised:
976
977 >>> np.bincount(np.arange(5, dtype=float))
978 Traceback (most recent call last):
979 ...
980 TypeError: Cannot cast array data from dtype('float64') to dtype('int64')
981 according to the rule 'safe'
982
983 A possible use of ``bincount`` is to perform sums over
984 variable-size chunks of an array, using the ``weights`` keyword.
985
986 >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
987 >>> x = np.array([0, 1, 1, 2, 2, 2])
988 >>> np.bincount(x, weights=w)
989 array([ 0.3, 0.7, 1.1])
990
991 """
992 return (x, weights)
993
994
995@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index)
996def ravel_multi_index(multi_index, dims, mode=None, order=None):
997 """
998 ravel_multi_index(multi_index, dims, mode='raise', order='C')
999
1000 Converts a tuple of index arrays into an array of flat
1001 indices, applying boundary modes to the multi-index.
1002
1003 Parameters
1004 ----------
1005 multi_index : tuple of array_like
1006 A tuple of integer arrays, one array for each dimension.
1007 dims : tuple of ints
1008 The shape of array into which the indices from ``multi_index`` apply.
1009 mode : {'raise', 'wrap', 'clip'}, optional
1010 Specifies how out-of-bounds indices are handled. Can specify
1011 either one mode or a tuple of modes, one mode per index.
1012
1013 * 'raise' -- raise an error (default)
1014 * 'wrap' -- wrap around
1015 * 'clip' -- clip to the range
1016
1017 In 'clip' mode, a negative index which would normally
1018 wrap will clip to 0 instead.
1019 order : {'C', 'F'}, optional
1020 Determines whether the multi-index should be viewed as
1021 indexing in row-major (C-style) or column-major
1022 (Fortran-style) order.
1023
1024 Returns
1025 -------
1026 raveled_indices : ndarray
1027 An array of indices into the flattened version of an array
1028 of dimensions ``dims``.
1029
1030 See Also
1031 --------
1032 unravel_index
1033
1034 Examples
1035 --------
1036 >>> import numpy as np
1037 >>> arr = np.array([[3,6,6],[4,5,1]])
1038 >>> np.ravel_multi_index(arr, (7,6))
1039 array([22, 41, 37])
1040 >>> np.ravel_multi_index(arr, (7,6), order='F')
1041 array([31, 41, 13])
1042 >>> np.ravel_multi_index(arr, (4,6), mode='clip')
1043 array([22, 23, 19])
1044 >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
1045 array([12, 13, 13])
1046
1047 >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
1048 1621
1049 """
1050 return multi_index
1051
1052
1053@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index)
1054def unravel_index(indices, shape=None, order=None):
1055 """
1056 unravel_index(indices, shape, order='C')
1057
1058 Converts a flat index or array of flat indices into a tuple
1059 of coordinate arrays.
1060
1061 Parameters
1062 ----------
1063 indices : array_like
1064 An integer array whose elements are indices into the flattened
1065 version of an array of dimensions ``shape``. Before version 1.6.0,
1066 this function accepted just one index value.
1067 shape : tuple of ints
1068 The shape of the array to use for unraveling ``indices``.
1069 order : {'C', 'F'}, optional
1070 Determines whether the indices should be viewed as indexing in
1071 row-major (C-style) or column-major (Fortran-style) order.
1072
1073 Returns
1074 -------
1075 unraveled_coords : tuple of ndarray
1076 Each array in the tuple has the same shape as the ``indices``
1077 array.
1078
1079 See Also
1080 --------
1081 ravel_multi_index
1082
1083 Examples
1084 --------
1085 >>> import numpy as np
1086 >>> np.unravel_index([22, 41, 37], (7,6))
1087 (array([3, 6, 6]), array([4, 5, 1]))
1088 >>> np.unravel_index([31, 41, 13], (7,6), order='F')
1089 (array([3, 6, 6]), array([4, 5, 1]))
1090
1091 >>> np.unravel_index(1621, (6,7,8,9))
1092 (3, 1, 4, 1)
1093
1094 """
1095 return (indices,)
1096
1097
1098@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto)
1099def copyto(dst, src, casting=None, where=None):
1100 """
1101 copyto(dst, src, casting='same_kind', where=True)
1102
1103 Copies values from one array to another, broadcasting as necessary.
1104
1105 Raises a TypeError if the `casting` rule is violated, and if
1106 `where` is provided, it selects which elements to copy.
1107
1108 Parameters
1109 ----------
1110 dst : ndarray
1111 The array into which values are copied.
1112 src : array_like
1113 The array from which values are copied.
1114 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
1115 Controls what kind of data casting may occur when copying.
1116
1117 * 'no' means the data types should not be cast at all.
1118 * 'equiv' means only byte-order changes are allowed.
1119 * 'safe' means only casts which can preserve values are allowed.
1120 * 'same_kind' means only safe casts or casts within a kind,
1121 like float64 to float32, are allowed.
1122 * 'unsafe' means any data conversions may be done.
1123 where : array_like of bool, optional
1124 A boolean array which is broadcasted to match the dimensions
1125 of `dst`, and selects elements to copy from `src` to `dst`
1126 wherever it contains the value True.
1127
1128 Examples
1129 --------
1130 >>> import numpy as np
1131 >>> A = np.array([4, 5, 6])
1132 >>> B = [1, 2, 3]
1133 >>> np.copyto(A, B)
1134 >>> A
1135 array([1, 2, 3])
1136
1137 >>> A = np.array([[1, 2, 3], [4, 5, 6]])
1138 >>> B = [[4, 5, 6], [7, 8, 9]]
1139 >>> np.copyto(A, B)
1140 >>> A
1141 array([[4, 5, 6],
1142 [7, 8, 9]])
1143
1144 """
1145 return (dst, src, where)
1146
1147
1148@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask)
1149def putmask(a, /, mask, values):
1150 """
1151 putmask(a, mask, values)
1152
1153 Changes elements of an array based on conditional and input values.
1154
1155 Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
1156
1157 If `values` is not the same size as `a` and `mask` then it will repeat.
1158 This gives behavior different from ``a[mask] = values``.
1159
1160 Parameters
1161 ----------
1162 a : ndarray
1163 Target array.
1164 mask : array_like
1165 Boolean mask array. It has to be the same shape as `a`.
1166 values : array_like
1167 Values to put into `a` where `mask` is True. If `values` is smaller
1168 than `a` it will be repeated.
1169
1170 See Also
1171 --------
1172 place, put, take, copyto
1173
1174 Examples
1175 --------
1176 >>> import numpy as np
1177 >>> x = np.arange(6).reshape(2, 3)
1178 >>> np.putmask(x, x>2, x**2)
1179 >>> x
1180 array([[ 0, 1, 2],
1181 [ 9, 16, 25]])
1182
1183 If `values` is smaller than `a` it is repeated:
1184
1185 >>> x = np.arange(5)
1186 >>> np.putmask(x, x>1, [-33, -44])
1187 >>> x
1188 array([ 0, 1, -33, -44, -33])
1189
1190 """
1191 return (a, mask, values)
1192
1193
1194@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits)
1195def packbits(a, axis=None, bitorder='big'):
1196 """
1197 packbits(a, /, axis=None, bitorder='big')
1198
1199 Packs the elements of a binary-valued array into bits in a uint8 array.
1200
1201 The result is padded to full bytes by inserting zero bits at the end.
1202
1203 Parameters
1204 ----------
1205 a : array_like
1206 An array of integers or booleans whose elements should be packed to
1207 bits.
1208 axis : int, optional
1209 The dimension over which bit-packing is done.
1210 ``None`` implies packing the flattened array.
1211 bitorder : {'big', 'little'}, optional
1212 The order of the input bits. 'big' will mimic bin(val),
1213 ``[0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011``, 'little' will
1214 reverse the order so ``[1, 1, 0, 0, 0, 0, 0, 0] => 3``.
1215 Defaults to 'big'.
1216
1217 Returns
1218 -------
1219 packed : ndarray
1220 Array of type uint8 whose elements represent bits corresponding to the
1221 logical (0 or nonzero) value of the input elements. The shape of
1222 `packed` has the same number of dimensions as the input (unless `axis`
1223 is None, in which case the output is 1-D).
1224
1225 See Also
1226 --------
1227 unpackbits: Unpacks elements of a uint8 array into a binary-valued output
1228 array.
1229
1230 Examples
1231 --------
1232 >>> import numpy as np
1233 >>> a = np.array([[[1,0,1],
1234 ... [0,1,0]],
1235 ... [[1,1,0],
1236 ... [0,0,1]]])
1237 >>> b = np.packbits(a, axis=-1)
1238 >>> b
1239 array([[[160],
1240 [ 64]],
1241 [[192],
1242 [ 32]]], dtype=uint8)
1243
1244 Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000,
1245 and 32 = 0010 0000.
1246
1247 """
1248 return (a,)
1249
1250
1251@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits)
1252def unpackbits(a, axis=None, count=None, bitorder='big'):
1253 """
1254 unpackbits(a, /, axis=None, count=None, bitorder='big')
1255
1256 Unpacks elements of a uint8 array into a binary-valued output array.
1257
1258 Each element of `a` represents a bit-field that should be unpacked
1259 into a binary-valued output array. The shape of the output array is
1260 either 1-D (if `axis` is ``None``) or the same shape as the input
1261 array with unpacking done along the axis specified.
1262
1263 Parameters
1264 ----------
1265 a : ndarray, uint8 type
1266 Input array.
1267 axis : int, optional
1268 The dimension over which bit-unpacking is done.
1269 ``None`` implies unpacking the flattened array.
1270 count : int or None, optional
1271 The number of elements to unpack along `axis`, provided as a way
1272 of undoing the effect of packing a size that is not a multiple
1273 of eight. A non-negative number means to only unpack `count`
1274 bits. A negative number means to trim off that many bits from
1275 the end. ``None`` means to unpack the entire array (the
1276 default). Counts larger than the available number of bits will
1277 add zero padding to the output. Negative counts must not
1278 exceed the available number of bits.
1279 bitorder : {'big', 'little'}, optional
1280 The order of the returned bits. 'big' will mimic bin(val),
1281 ``3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1]``, 'little' will reverse
1282 the order to ``[1, 1, 0, 0, 0, 0, 0, 0]``.
1283 Defaults to 'big'.
1284
1285 Returns
1286 -------
1287 unpacked : ndarray, uint8 type
1288 The elements are binary-valued (0 or 1).
1289
1290 See Also
1291 --------
1292 packbits : Packs the elements of a binary-valued array into bits in
1293 a uint8 array.
1294
1295 Examples
1296 --------
1297 >>> import numpy as np
1298 >>> a = np.array([[2], [7], [23]], dtype=np.uint8)
1299 >>> a
1300 array([[ 2],
1301 [ 7],
1302 [23]], dtype=uint8)
1303 >>> b = np.unpackbits(a, axis=1)
1304 >>> b
1305 array([[0, 0, 0, 0, 0, 0, 1, 0],
1306 [0, 0, 0, 0, 0, 1, 1, 1],
1307 [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
1308 >>> c = np.unpackbits(a, axis=1, count=-3)
1309 >>> c
1310 array([[0, 0, 0, 0, 0],
1311 [0, 0, 0, 0, 0],
1312 [0, 0, 0, 1, 0]], dtype=uint8)
1313
1314 >>> p = np.packbits(b, axis=0)
1315 >>> np.unpackbits(p, axis=0)
1316 array([[0, 0, 0, 0, 0, 0, 1, 0],
1317 [0, 0, 0, 0, 0, 1, 1, 1],
1318 [0, 0, 0, 1, 0, 1, 1, 1],
1319 [0, 0, 0, 0, 0, 0, 0, 0],
1320 [0, 0, 0, 0, 0, 0, 0, 0],
1321 [0, 0, 0, 0, 0, 0, 0, 0],
1322 [0, 0, 0, 0, 0, 0, 0, 0],
1323 [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
1324 >>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0]))
1325 True
1326
1327 """
1328 return (a,)
1329
1330
1331@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory)
1332def shares_memory(a, b, max_work=None):
1333 """
1334 shares_memory(a, b, /, max_work=None)
1335
1336 Determine if two arrays share memory.
1337
1338 .. warning::
1339
1340 This function can be exponentially slow for some inputs, unless
1341 `max_work` is set to zero or a positive integer.
1342 If in doubt, use `numpy.may_share_memory` instead.
1343
1344 Parameters
1345 ----------
1346 a, b : ndarray
1347 Input arrays
1348 max_work : int, optional
1349 Effort to spend on solving the overlap problem (maximum number
1350 of candidate solutions to consider). The following special
1351 values are recognized:
1352
1353 max_work=-1 (default)
1354 The problem is solved exactly. In this case, the function returns
1355 True only if there is an element shared between the arrays. Finding
1356 the exact solution may take extremely long in some cases.
1357 max_work=0
1358 Only the memory bounds of a and b are checked.
1359 This is equivalent to using ``may_share_memory()``.
1360
1361 Raises
1362 ------
1363 numpy.exceptions.TooHardError
1364 Exceeded max_work.
1365
1366 Returns
1367 -------
1368 out : bool
1369
1370 See Also
1371 --------
1372 may_share_memory
1373
1374 Examples
1375 --------
1376 >>> import numpy as np
1377 >>> x = np.array([1, 2, 3, 4])
1378 >>> np.shares_memory(x, np.array([5, 6, 7]))
1379 False
1380 >>> np.shares_memory(x[::2], x)
1381 True
1382 >>> np.shares_memory(x[::2], x[1::2])
1383 False
1384
1385 Checking whether two arrays share memory is NP-complete, and
1386 runtime may increase exponentially in the number of
1387 dimensions. Hence, `max_work` should generally be set to a finite
1388 number, as it is possible to construct examples that take
1389 extremely long to run:
1390
1391 >>> from numpy.lib.stride_tricks import as_strided
1392 >>> x = np.zeros([192163377], dtype=np.int8)
1393 >>> x1 = as_strided(
1394 ... x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049))
1395 >>> x2 = as_strided(
1396 ... x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1))
1397 >>> np.shares_memory(x1, x2, max_work=1000)
1398 Traceback (most recent call last):
1399 ...
1400 numpy.exceptions.TooHardError: Exceeded max_work
1401
1402 Running ``np.shares_memory(x1, x2)`` without `max_work` set takes
1403 around 1 minute for this case. It is possible to find problems
1404 that take still significantly longer.
1405
1406 """
1407 return (a, b)
1408
1409
1410@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory)
1411def may_share_memory(a, b, max_work=None):
1412 """
1413 may_share_memory(a, b, /, max_work=None)
1414
1415 Determine if two arrays might share memory
1416
1417 A return of True does not necessarily mean that the two arrays
1418 share any element. It just means that they *might*.
1419
1420 Only the memory bounds of a and b are checked by default.
1421
1422 Parameters
1423 ----------
1424 a, b : ndarray
1425 Input arrays
1426 max_work : int, optional
1427 Effort to spend on solving the overlap problem. See
1428 `shares_memory` for details. Default for ``may_share_memory``
1429 is to do a bounds check.
1430
1431 Returns
1432 -------
1433 out : bool
1434
1435 See Also
1436 --------
1437 shares_memory
1438
1439 Examples
1440 --------
1441 >>> import numpy as np
1442 >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
1443 False
1444 >>> x = np.zeros([3, 4])
1445 >>> np.may_share_memory(x[:,0], x[:,1])
1446 True
1447
1448 """
1449 return (a, b)
1450
1451
1452@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday)
1453def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None):
1454 """
1455 is_busday(
1456 dates,
1457 weekmask='1111100',
1458 holidays=None,
1459 busdaycal=None,
1460 out=None
1461 )
1462
1463 Calculates which of the given dates are valid days, and which are not.
1464
1465 Parameters
1466 ----------
1467 dates : array_like of datetime64[D]
1468 The array of dates to process.
1469 weekmask : str or array_like of bool, optional
1470 A seven-element array indicating which of Monday through Sunday are
1471 valid days. May be specified as a length-seven list or array, like
1472 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
1473 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
1474 weekdays, optionally separated by white space. Valid abbreviations
1475 are: Mon Tue Wed Thu Fri Sat Sun
1476 holidays : array_like of datetime64[D], optional
1477 An array of dates to consider as invalid dates. They may be
1478 specified in any order, and NaT (not-a-time) dates are ignored.
1479 This list is saved in a normalized form that is suited for
1480 fast calculations of valid days.
1481 busdaycal : busdaycalendar, optional
1482 A `busdaycalendar` object which specifies the valid days. If this
1483 parameter is provided, neither weekmask nor holidays may be
1484 provided.
1485 out : array of bool, optional
1486 If provided, this array is filled with the result.
1487
1488 Returns
1489 -------
1490 out : array of bool
1491 An array with the same shape as ``dates``, containing True for
1492 each valid day, and False for each invalid day.
1493
1494 See Also
1495 --------
1496 busdaycalendar : An object that specifies a custom set of valid days.
1497 busday_offset : Applies an offset counted in valid days.
1498 busday_count : Counts how many valid days are in a half-open date range.
1499
1500 Examples
1501 --------
1502 >>> import numpy as np
1503 >>> # The weekdays are Friday, Saturday, and Monday
1504 ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'],
1505 ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
1506 array([False, False, True])
1507 """
1508 return (dates, weekmask, holidays, out)
1509
1510
1511@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset)
1512def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None,
1513 busdaycal=None, out=None):
1514 """
1515 busday_offset(
1516 dates,
1517 offsets,
1518 roll='raise',
1519 weekmask='1111100',
1520 holidays=None,
1521 busdaycal=None,
1522 out=None
1523 )
1524
1525 First adjusts the date to fall on a valid day according to
1526 the ``roll`` rule, then applies offsets to the given dates
1527 counted in valid days.
1528
1529 Parameters
1530 ----------
1531 dates : array_like of datetime64[D]
1532 The array of dates to process.
1533 offsets : array_like of int
1534 The array of offsets, which is broadcast with ``dates``.
1535 roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', \
1536 'modifiedfollowing', 'modifiedpreceding'}, optional
1537 How to treat dates that do not fall on a valid day. The default
1538 is 'raise'.
1539
1540 * 'raise' means to raise an exception for an invalid day.
1541 * 'nat' means to return a NaT (not-a-time) for an invalid day.
1542 * 'forward' and 'following' mean to take the first valid day
1543 later in time.
1544 * 'backward' and 'preceding' mean to take the first valid day
1545 earlier in time.
1546 * 'modifiedfollowing' means to take the first valid day
1547 later in time unless it is across a Month boundary, in which
1548 case to take the first valid day earlier in time.
1549 * 'modifiedpreceding' means to take the first valid day
1550 earlier in time unless it is across a Month boundary, in which
1551 case to take the first valid day later in time.
1552 weekmask : str or array_like of bool, optional
1553 A seven-element array indicating which of Monday through Sunday are
1554 valid days. May be specified as a length-seven list or array, like
1555 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
1556 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
1557 weekdays, optionally separated by white space. Valid abbreviations
1558 are: Mon Tue Wed Thu Fri Sat Sun
1559 holidays : array_like of datetime64[D], optional
1560 An array of dates to consider as invalid dates. They may be
1561 specified in any order, and NaT (not-a-time) dates are ignored.
1562 This list is saved in a normalized form that is suited for
1563 fast calculations of valid days.
1564 busdaycal : busdaycalendar, optional
1565 A `busdaycalendar` object which specifies the valid days. If this
1566 parameter is provided, neither weekmask nor holidays may be
1567 provided.
1568 out : array of datetime64[D], optional
1569 If provided, this array is filled with the result.
1570
1571 Returns
1572 -------
1573 out : array of datetime64[D]
1574 An array with a shape from broadcasting ``dates`` and ``offsets``
1575 together, containing the dates with offsets applied.
1576
1577 See Also
1578 --------
1579 busdaycalendar : An object that specifies a custom set of valid days.
1580 is_busday : Returns a boolean array indicating valid days.
1581 busday_count : Counts how many valid days are in a half-open date range.
1582
1583 Examples
1584 --------
1585 >>> import numpy as np
1586 >>> # First business day in October 2011 (not accounting for holidays)
1587 ... np.busday_offset('2011-10', 0, roll='forward')
1588 np.datetime64('2011-10-03')
1589 >>> # Last business day in February 2012 (not accounting for holidays)
1590 ... np.busday_offset('2012-03', -1, roll='forward')
1591 np.datetime64('2012-02-29')
1592 >>> # Third Wednesday in January 2011
1593 ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
1594 np.datetime64('2011-01-19')
1595 >>> # 2012 Mother's Day in Canada and the U.S.
1596 ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
1597 np.datetime64('2012-05-13')
1598
1599 >>> # First business day on or after a date
1600 ... np.busday_offset('2011-03-20', 0, roll='forward')
1601 np.datetime64('2011-03-21')
1602 >>> np.busday_offset('2011-03-22', 0, roll='forward')
1603 np.datetime64('2011-03-22')
1604 >>> # First business day after a date
1605 ... np.busday_offset('2011-03-20', 1, roll='backward')
1606 np.datetime64('2011-03-21')
1607 >>> np.busday_offset('2011-03-22', 1, roll='backward')
1608 np.datetime64('2011-03-23')
1609 """
1610 return (dates, offsets, weekmask, holidays, out)
1611
1612
1613@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count)
1614def busday_count(begindates, enddates, weekmask=None, holidays=None,
1615 busdaycal=None, out=None):
1616 """
1617 busday_count(
1618 begindates,
1619 enddates,
1620 weekmask='1111100',
1621 holidays=[],
1622 busdaycal=None,
1623 out=None
1624 )
1625
1626 Counts the number of valid days between `begindates` and
1627 `enddates`, not including the day of `enddates`.
1628
1629 If ``enddates`` specifies a date value that is earlier than the
1630 corresponding ``begindates`` date value, the count will be negative.
1631
1632 Parameters
1633 ----------
1634 begindates : array_like of datetime64[D]
1635 The array of the first dates for counting.
1636 enddates : array_like of datetime64[D]
1637 The array of the end dates for counting, which are excluded
1638 from the count themselves.
1639 weekmask : str or array_like of bool, optional
1640 A seven-element array indicating which of Monday through Sunday are
1641 valid days. May be specified as a length-seven list or array, like
1642 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
1643 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
1644 weekdays, optionally separated by white space. Valid abbreviations
1645 are: Mon Tue Wed Thu Fri Sat Sun
1646 holidays : array_like of datetime64[D], optional
1647 An array of dates to consider as invalid dates. They may be
1648 specified in any order, and NaT (not-a-time) dates are ignored.
1649 This list is saved in a normalized form that is suited for
1650 fast calculations of valid days.
1651 busdaycal : busdaycalendar, optional
1652 A `busdaycalendar` object which specifies the valid days. If this
1653 parameter is provided, neither weekmask nor holidays may be
1654 provided.
1655 out : array of int, optional
1656 If provided, this array is filled with the result.
1657
1658 Returns
1659 -------
1660 out : array of int
1661 An array with a shape from broadcasting ``begindates`` and ``enddates``
1662 together, containing the number of valid days between
1663 the begin and end dates.
1664
1665 See Also
1666 --------
1667 busdaycalendar : An object that specifies a custom set of valid days.
1668 is_busday : Returns a boolean array indicating valid days.
1669 busday_offset : Applies an offset counted in valid days.
1670
1671 Examples
1672 --------
1673 >>> import numpy as np
1674 >>> # Number of weekdays in January 2011
1675 ... np.busday_count('2011-01', '2011-02')
1676 21
1677 >>> # Number of weekdays in 2011
1678 >>> np.busday_count('2011', '2012')
1679 260
1680 >>> # Number of Saturdays in 2011
1681 ... np.busday_count('2011', '2012', weekmask='Sat')
1682 53
1683 """
1684 return (begindates, enddates, weekmask, holidays, out)
1685
1686
1687@array_function_from_c_func_and_dispatcher(
1688 _multiarray_umath.datetime_as_string)
1689def datetime_as_string(arr, unit=None, timezone=None, casting=None):
1690 """
1691 datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
1692
1693 Convert an array of datetimes into an array of strings.
1694
1695 Parameters
1696 ----------
1697 arr : array_like of datetime64
1698 The array of UTC timestamps to format.
1699 unit : str
1700 One of None, 'auto', or
1701 a :ref:`datetime unit <arrays.dtypes.dateunits>`.
1702 timezone : {'naive', 'UTC', 'local'} or tzinfo
1703 Timezone information to use when displaying the datetime. If 'UTC',
1704 end with a Z to indicate UTC time. If 'local', convert to the local
1705 timezone first, and suffix with a +-#### timezone offset. If a tzinfo
1706 object, then do as with 'local', but use the specified timezone.
1707 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
1708 Casting to allow when changing between datetime units.
1709
1710 Returns
1711 -------
1712 str_arr : ndarray
1713 An array of strings the same shape as `arr`.
1714
1715 Examples
1716 --------
1717 >>> import numpy as np
1718 >>> import pytz
1719 >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
1720 >>> d
1721 array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
1722 '2002-10-27T07:30'], dtype='datetime64[m]')
1723
1724 Setting the timezone to UTC shows the same information, but with a Z suffix
1725
1726 >>> np.datetime_as_string(d, timezone='UTC')
1727 array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
1728 '2002-10-27T07:30Z'], dtype='<U35')
1729
1730 Note that we picked datetimes that cross a DST boundary. Passing in a
1731 ``pytz`` timezone object will print the appropriate offset
1732
1733 >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
1734 array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
1735 '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')
1736
1737 Passing in a unit will change the precision
1738
1739 >>> np.datetime_as_string(d, unit='h')
1740 array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
1741 dtype='<U32')
1742 >>> np.datetime_as_string(d, unit='s')
1743 array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
1744 '2002-10-27T07:30:00'], dtype='<U38')
1745
1746 'casting' can be used to specify whether precision can be changed
1747
1748 >>> np.datetime_as_string(d, unit='h', casting='safe')
1749 Traceback (most recent call last):
1750 ...
1751 TypeError: Cannot create a datetime string as units 'h' from a NumPy
1752 datetime with units 'm' according to the rule 'safe'
1753 """
1754 return (arr,)