Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
numeric.py2772 linesDownload Raw Back to _core
1import builtins
2import functools
3import itertools
4import math
5import numbers
6import operator
7import sys
8import warnings
9
10import numpy as np
11from numpy.exceptions import AxisError
12
13from . import multiarray, numerictypes, numerictypes as nt, overrides, shape_base, umath
14from ._ufunc_config import errstate
15from .multiarray import (  # noqa: F401
16    ALLOW_THREADS,
17    BUFSIZE,
18    CLIP,
19    MAXDIMS,
20    MAY_SHARE_BOUNDS,
21    MAY_SHARE_EXACT,
22    RAISE,
23    WRAP,
24    arange,
25    array,
26    asanyarray,
27    asarray,
28    ascontiguousarray,
29    asfortranarray,
30    broadcast,
31    can_cast,
32    concatenate,
33    copyto,
34    dot,
35    dtype,
36    empty,
37    empty_like,
38    flatiter,
39    from_dlpack,
40    frombuffer,
41    fromfile,
42    fromiter,
43    fromstring,
44    inner,
45    lexsort,
46    matmul,
47    may_share_memory,
48    min_scalar_type,
49    ndarray,
50    nditer,
51    nested_iters,
52    normalize_axis_index,
53    promote_types,
54    putmask,
55    result_type,
56    shares_memory,
57    vdot,
58    vecdot,
59    where,
60    zeros,
61)
62from .overrides import finalize_array_function_like, set_module
63from .umath import NAN, PINF, invert, multiply, sin
64
65bitwise_not = invert
66ufunc = type(sin)
67newaxis = None
68
69array_function_dispatch = functools.partial(
70    overrides.array_function_dispatch, module='numpy')
71
72
73__all__ = [
74    'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
75    'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray',
76    'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype',
77    'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where',
78    'argwhere', 'copyto', 'concatenate', 'lexsort', 'astype',
79    'can_cast', 'promote_types', 'min_scalar_type',
80    'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
81    'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
82    'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
83    'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
84    'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones',
85    'identity', 'allclose', 'putmask',
86    'flatnonzero', 'inf', 'nan', 'False_', 'True_', 'bitwise_not',
87    'full', 'full_like', 'matmul', 'vecdot', 'shares_memory',
88    'may_share_memory']
89
90
91def _zeros_like_dispatcher(
92    a, dtype=None, order=None, subok=None, shape=None, *, device=None
93):
94    return (a,)
95
96
97@array_function_dispatch(_zeros_like_dispatcher)
98def zeros_like(
99    a, dtype=None, order='K', subok=True, shape=None, *, device=None
100):
101    """
102    Return an array of zeros with the same shape and type as a given array.
103
104    Parameters
105    ----------
106    a : array_like
107        The shape and data-type of `a` define these same attributes of
108        the returned array.
109    dtype : data-type, optional
110        Overrides the data type of the result.
111    order : {'C', 'F', 'A', or 'K'}, optional
112        Overrides the memory layout of the result. 'C' means C-order,
113        'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
114        'C' otherwise. 'K' means match the layout of `a` as closely
115        as possible.
116    subok : bool, optional.
117        If True, then the newly created array will use the sub-class
118        type of `a`, otherwise it will be a base-class array. Defaults
119        to True.
120    shape : int or sequence of ints, optional.
121        Overrides the shape of the result. If order='K' and the number of
122        dimensions is unchanged, will try to keep order, otherwise,
123        order='C' is implied.
124    device : str, optional
125        The device on which to place the created array. Default: None.
126        For Array-API interoperability only, so must be ``"cpu"`` if passed.
127
128        .. versionadded:: 2.0.0
129
130    Returns
131    -------
132    out : ndarray
133        Array of zeros with the same shape and type as `a`.
134
135    See Also
136    --------
137    empty_like : Return an empty array with shape and type of input.
138    ones_like : Return an array of ones with shape and type of input.
139    full_like : Return a new array with shape of input filled with value.
140    zeros : Return a new array setting values to zero.
141
142    Examples
143    --------
144    >>> import numpy as np
145    >>> x = np.arange(6)
146    >>> x = x.reshape((2, 3))
147    >>> x
148    array([[0, 1, 2],
149           [3, 4, 5]])
150    >>> np.zeros_like(x)
151    array([[0, 0, 0],
152           [0, 0, 0]])
153
154    >>> y = np.arange(3, dtype=float)
155    >>> y
156    array([0., 1., 2.])
157    >>> np.zeros_like(y)
158    array([0.,  0.,  0.])
159
160    """
161    res = empty_like(
162        a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
163    )
164    # needed instead of a 0 to get same result as zeros for string dtypes
165    z = zeros(1, dtype=res.dtype)
166    multiarray.copyto(res, z, casting='unsafe')
167    return res
168
169
170@finalize_array_function_like
171@set_module('numpy')
172def ones(shape, dtype=None, order='C', *, device=None, like=None):
173    """
174    Return a new array of given shape and type, filled with ones.
175
176    Parameters
177    ----------
178    shape : int or sequence of ints
179        Shape of the new array, e.g., ``(2, 3)`` or ``2``.
180    dtype : data-type, optional
181        The desired data-type for the array, e.g., `numpy.int8`.  Default is
182        `numpy.float64`.
183    order : {'C', 'F'}, optional, default: C
184        Whether to store multi-dimensional data in row-major
185        (C-style) or column-major (Fortran-style) order in
186        memory.
187    device : str, optional
188        The device on which to place the created array. Default: None.
189        For Array-API interoperability only, so must be ``"cpu"`` if passed.
190
191        .. versionadded:: 2.0.0
192    ${ARRAY_FUNCTION_LIKE}
193
194        .. versionadded:: 1.20.0
195
196    Returns
197    -------
198    out : ndarray
199        Array of ones with the given shape, dtype, and order.
200
201    See Also
202    --------
203    ones_like : Return an array of ones with shape and type of input.
204    empty : Return a new uninitialized array.
205    zeros : Return a new array setting values to zero.
206    full : Return a new array of given shape filled with value.
207
208    Examples
209    --------
210    >>> import numpy as np
211    >>> np.ones(5)
212    array([1., 1., 1., 1., 1.])
213
214    >>> np.ones((5,), dtype=int)
215    array([1, 1, 1, 1, 1])
216
217    >>> np.ones((2, 1))
218    array([[1.],
219           [1.]])
220
221    >>> s = (2,2)
222    >>> np.ones(s)
223    array([[1.,  1.],
224           [1.,  1.]])
225
226    """
227    if like is not None:
228        return _ones_with_like(
229            like, shape, dtype=dtype, order=order, device=device
230        )
231
232    a = empty(shape, dtype, order, device=device)
233    multiarray.copyto(a, 1, casting='unsafe')
234    return a
235
236
237_ones_with_like = array_function_dispatch()(ones)
238
239
240def _ones_like_dispatcher(
241    a, dtype=None, order=None, subok=None, shape=None, *, device=None
242):
243    return (a,)
244
245
246@array_function_dispatch(_ones_like_dispatcher)
247def ones_like(
248    a, dtype=None, order='K', subok=True, shape=None, *, device=None
249):
250    """
251    Return an array of ones with the same shape and type as a given array.
252
253    Parameters
254    ----------
255    a : array_like
256        The shape and data-type of `a` define these same attributes of
257        the returned array.
258    dtype : data-type, optional
259        Overrides the data type of the result.
260    order : {'C', 'F', 'A', or 'K'}, optional
261        Overrides the memory layout of the result. 'C' means C-order,
262        'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
263        'C' otherwise. 'K' means match the layout of `a` as closely
264        as possible.
265    subok : bool, optional.
266        If True, then the newly created array will use the sub-class
267        type of `a`, otherwise it will be a base-class array. Defaults
268        to True.
269    shape : int or sequence of ints, optional.
270        Overrides the shape of the result. If order='K' and the number of
271        dimensions is unchanged, will try to keep order, otherwise,
272        order='C' is implied.
273    device : str, optional
274        The device on which to place the created array. Default: None.
275        For Array-API interoperability only, so must be ``"cpu"`` if passed.
276
277        .. versionadded:: 2.0.0
278
279    Returns
280    -------
281    out : ndarray
282        Array of ones with the same shape and type as `a`.
283
284    See Also
285    --------
286    empty_like : Return an empty array with shape and type of input.
287    zeros_like : Return an array of zeros with shape and type of input.
288    full_like : Return a new array with shape of input filled with value.
289    ones : Return a new array setting values to one.
290
291    Examples
292    --------
293    >>> import numpy as np
294    >>> x = np.arange(6)
295    >>> x = x.reshape((2, 3))
296    >>> x
297    array([[0, 1, 2],
298           [3, 4, 5]])
299    >>> np.ones_like(x)
300    array([[1, 1, 1],
301           [1, 1, 1]])
302
303    >>> y = np.arange(3, dtype=float)
304    >>> y
305    array([0., 1., 2.])
306    >>> np.ones_like(y)
307    array([1.,  1.,  1.])
308
309    """
310    res = empty_like(
311        a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
312    )
313    multiarray.copyto(res, 1, casting='unsafe')
314    return res
315
316
317def _full_dispatcher(
318    shape, fill_value, dtype=None, order=None, *, device=None, like=None
319):
320    return (like,)
321
322
323@finalize_array_function_like
324@set_module('numpy')
325def full(shape, fill_value, dtype=None, order='C', *, device=None, like=None):
326    """
327    Return a new array of given shape and type, filled with `fill_value`.
328
329    Parameters
330    ----------
331    shape : int or sequence of ints
332        Shape of the new array, e.g., ``(2, 3)`` or ``2``.
333    fill_value : scalar or array_like
334        Fill value.
335    dtype : data-type, optional
336        The desired data-type for the array  The default, None, means
337         ``np.array(fill_value).dtype``.
338    order : {'C', 'F'}, optional
339        Whether to store multidimensional data in C- or Fortran-contiguous
340        (row- or column-wise) order in memory.
341    device : str, optional
342        The device on which to place the created array. Default: None.
343        For Array-API interoperability only, so must be ``"cpu"`` if passed.
344
345        .. versionadded:: 2.0.0
346    ${ARRAY_FUNCTION_LIKE}
347
348        .. versionadded:: 1.20.0
349
350    Returns
351    -------
352    out : ndarray
353        Array of `fill_value` with the given shape, dtype, and order.
354
355    See Also
356    --------
357    full_like : Return a new array with shape of input filled with value.
358    empty : Return a new uninitialized array.
359    ones : Return a new array setting values to one.
360    zeros : Return a new array setting values to zero.
361
362    Examples
363    --------
364    >>> import numpy as np
365    >>> np.full((2, 2), np.inf)
366    array([[inf, inf],
367           [inf, inf]])
368    >>> np.full((2, 2), 10)
369    array([[10, 10],
370           [10, 10]])
371
372    >>> np.full((2, 2), [1, 2])
373    array([[1, 2],
374           [1, 2]])
375
376    """
377    if like is not None:
378        return _full_with_like(
379            like, shape, fill_value, dtype=dtype, order=order, device=device
380        )
381
382    if dtype is None:
383        fill_value = asarray(fill_value)
384        dtype = fill_value.dtype
385    a = empty(shape, dtype, order, device=device)
386    multiarray.copyto(a, fill_value, casting='unsafe')
387    return a
388
389
390_full_with_like = array_function_dispatch()(full)
391
392
393def _full_like_dispatcher(
394    a, fill_value, dtype=None, order=None, subok=None, shape=None,
395    *, device=None
396):
397    return (a,)
398
399
400@array_function_dispatch(_full_like_dispatcher)
401def full_like(
402    a, fill_value, dtype=None, order='K', subok=True, shape=None,
403    *, device=None
404):
405    """
406    Return a full array with the same shape and type as a given array.
407
408    Parameters
409    ----------
410    a : array_like
411        The shape and data-type of `a` define these same attributes of
412        the returned array.
413    fill_value : array_like
414        Fill value.
415    dtype : data-type, optional
416        Overrides the data type of the result.
417    order : {'C', 'F', 'A', or 'K'}, optional
418        Overrides the memory layout of the result. 'C' means C-order,
419        'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
420        'C' otherwise. 'K' means match the layout of `a` as closely
421        as possible.
422    subok : bool, optional.
423        If True, then the newly created array will use the sub-class
424        type of `a`, otherwise it will be a base-class array. Defaults
425        to True.
426    shape : int or sequence of ints, optional.
427        Overrides the shape of the result. If order='K' and the number of
428        dimensions is unchanged, will try to keep order, otherwise,
429        order='C' is implied.
430    device : str, optional
431        The device on which to place the created array. Default: None.
432        For Array-API interoperability only, so must be ``"cpu"`` if passed.
433
434        .. versionadded:: 2.0.0
435
436    Returns
437    -------
438    out : ndarray
439        Array of `fill_value` with the same shape and type as `a`.
440
441    See Also
442    --------
443    empty_like : Return an empty array with shape and type of input.
444    ones_like : Return an array of ones with shape and type of input.
445    zeros_like : Return an array of zeros with shape and type of input.
446    full : Return a new array of given shape filled with value.
447
448    Examples
449    --------
450    >>> import numpy as np
451    >>> x = np.arange(6, dtype=int)
452    >>> np.full_like(x, 1)
453    array([1, 1, 1, 1, 1, 1])
454    >>> np.full_like(x, 0.1)
455    array([0, 0, 0, 0, 0, 0])
456    >>> np.full_like(x, 0.1, dtype=np.double)
457    array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
458    >>> np.full_like(x, np.nan, dtype=np.double)
459    array([nan, nan, nan, nan, nan, nan])
460
461    >>> y = np.arange(6, dtype=np.double)
462    >>> np.full_like(y, 0.1)
463    array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
464
465    >>> y = np.zeros([2, 2, 3], dtype=int)
466    >>> np.full_like(y, [0, 0, 255])
467    array([[[  0,   0, 255],
468            [  0,   0, 255]],
469           [[  0,   0, 255],
470            [  0,   0, 255]]])
471    """
472    res = empty_like(
473        a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
474    )
475    multiarray.copyto(res, fill_value, casting='unsafe')
476    return res
477
478
479def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
480    return (a,)
481
482
483@array_function_dispatch(_count_nonzero_dispatcher)
484def count_nonzero(a, axis=None, *, keepdims=False):
485    """
486    Counts the number of non-zero values in the array ``a``.
487
488    The word "non-zero" is in reference to the Python 2.x
489    built-in method ``__nonzero__()`` (renamed ``__bool__()``
490    in Python 3.x) of Python objects that tests an object's
491    "truthfulness". For example, any number is considered
492    truthful if it is nonzero, whereas any string is considered
493    truthful if it is not the empty string. Thus, this function
494    (recursively) counts how many elements in ``a`` (and in
495    sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
496    method evaluated to ``True``.
497
498    Parameters
499    ----------
500    a : array_like
501        The array for which to count non-zeros.
502    axis : int or tuple, optional
503        Axis or tuple of axes along which to count non-zeros.
504        Default is None, meaning that non-zeros will be counted
505        along a flattened version of ``a``.
506    keepdims : bool, optional
507        If this is set to True, the axes that are counted are left
508        in the result as dimensions with size one. With this option,
509        the result will broadcast correctly against the input array.
510
511    Returns
512    -------
513    count : int or array of int
514        Number of non-zero values in the array along a given axis.
515        Otherwise, the total number of non-zero values in the array
516        is returned.
517
518    See Also
519    --------
520    nonzero : Return the coordinates of all the non-zero values.
521
522    Examples
523    --------
524    >>> import numpy as np
525    >>> np.count_nonzero(np.eye(4))
526    np.int64(4)
527    >>> a = np.array([[0, 1, 7, 0],
528    ...               [3, 0, 2, 19]])
529    >>> np.count_nonzero(a)
530    np.int64(5)
531    >>> np.count_nonzero(a, axis=0)
532    array([1, 1, 2, 1])
533    >>> np.count_nonzero(a, axis=1)
534    array([2, 3])
535    >>> np.count_nonzero(a, axis=1, keepdims=True)
536    array([[2],
537           [3]])
538    """
539    if axis is None and not keepdims:
540        return multiarray.count_nonzero(a)
541
542    a = asanyarray(a)
543
544    # TODO: this works around .astype(bool) not working properly (gh-9847)
545    if np.issubdtype(a.dtype, np.character):
546        a_bool = a != a.dtype.type()
547    else:
548        a_bool = a.astype(np.bool, copy=False)
549
550    return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
551
552
553@set_module('numpy')
554def isfortran(a):
555    """
556    Check if the array is Fortran contiguous but *not* C contiguous.
557
558    This function is obsolete. If you only want to check if an array is Fortran
559    contiguous use ``a.flags.f_contiguous`` instead.
560
561    Parameters
562    ----------
563    a : ndarray
564        Input array.
565
566    Returns
567    -------
568    isfortran : bool
569        Returns True if the array is Fortran contiguous but *not* C contiguous.
570
571
572    Examples
573    --------
574
575    np.array allows to specify whether the array is written in C-contiguous
576    order (last index varies the fastest), or FORTRAN-contiguous order in
577    memory (first index varies the fastest).
578
579    >>> import numpy as np
580    >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
581    >>> a
582    array([[1, 2, 3],
583           [4, 5, 6]])
584    >>> np.isfortran(a)
585    False
586
587    >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
588    >>> b
589    array([[1, 2, 3],
590           [4, 5, 6]])
591    >>> np.isfortran(b)
592    True
593
594
595    The transpose of a C-ordered array is a FORTRAN-ordered array.
596
597    >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
598    >>> a
599    array([[1, 2, 3],
600           [4, 5, 6]])
601    >>> np.isfortran(a)
602    False
603    >>> b = a.T
604    >>> b
605    array([[1, 4],
606           [2, 5],
607           [3, 6]])
608    >>> np.isfortran(b)
609    True
610
611    C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
612
613    >>> np.isfortran(np.array([1, 2], order='F'))
614    False
615
616    """
617    return a.flags.fnc
618
619
620def _argwhere_dispatcher(a):
621    return (a,)
622
623
624@array_function_dispatch(_argwhere_dispatcher)
625def argwhere(a):
626    """
627    Find the indices of array elements that are non-zero, grouped by element.
628
629    Parameters
630    ----------
631    a : array_like
632        Input data.
633
634    Returns
635    -------
636    index_array : (N, a.ndim) ndarray
637        Indices of elements that are non-zero. Indices are grouped by element.
638        This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
639        non-zero items.
640
641    See Also
642    --------
643    where, nonzero
644
645    Notes
646    -----
647    ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
648    but produces a result of the correct shape for a 0D array.
649
650    The output of ``argwhere`` is not suitable for indexing arrays.
651    For this purpose use ``nonzero(a)`` instead.
652
653    Examples
654    --------
655    >>> import numpy as np
656    >>> x = np.arange(6).reshape(2,3)
657    >>> x
658    array([[0, 1, 2],
659           [3, 4, 5]])
660    >>> np.argwhere(x>1)
661    array([[0, 2],
662           [1, 0],
663           [1, 1],
664           [1, 2]])
665
666    """
667    # nonzero does not behave well on 0d, so promote to 1d
668    if np.ndim(a) == 0:
669        a = shape_base.atleast_1d(a)
670        # then remove the added dimension
671        return argwhere(a)[:, :0]
672    return transpose(nonzero(a))
673
674
675def _flatnonzero_dispatcher(a):
676    return (a,)
677
678
679@array_function_dispatch(_flatnonzero_dispatcher)
680def flatnonzero(a):
681    """
682    Return indices that are non-zero in the flattened version of a.
683
684    This is equivalent to ``np.nonzero(np.ravel(a))[0]``.
685
686    Parameters
687    ----------
688    a : array_like
689        Input data.
690
691    Returns
692    -------
693    res : ndarray
694        Output array, containing the indices of the elements of ``a.ravel()``
695        that are non-zero.
696
697    See Also
698    --------
699    nonzero : Return the indices of the non-zero elements of the input array.
700    ravel : Return a 1-D array containing the elements of the input array.
701
702    Examples
703    --------
704    >>> import numpy as np
705    >>> x = np.arange(-2, 3)
706    >>> x
707    array([-2, -1,  0,  1,  2])
708    >>> np.flatnonzero(x)
709    array([0, 1, 3, 4])
710
711    Use the indices of the non-zero elements as an index array to extract
712    these elements:
713
714    >>> x.ravel()[np.flatnonzero(x)]
715    array([-2, -1,  1,  2])
716
717    """
718    return np.nonzero(np.ravel(a))[0]
719
720
721def _correlate_dispatcher(a, v, mode=None):
722    return (a, v)
723
724
725@array_function_dispatch(_correlate_dispatcher)
726def correlate(a, v, mode='valid'):
727    r"""
728    Cross-correlation of two 1-dimensional sequences.
729
730    This function computes the correlation as generally defined in signal
731    processing texts [1]_:
732
733    .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v}_n
734
735    with a and v sequences being zero-padded where necessary and
736    :math:`\overline v` denoting complex conjugation.
737
738    Parameters
739    ----------
740    a, v : array_like
741        Input sequences.
742    mode : {'valid', 'same', 'full'}, optional
743        Refer to the `convolve` docstring.  Note that the default
744        is 'valid', unlike `convolve`, which uses 'full'.
745
746    Returns
747    -------
748    out : ndarray
749        Discrete cross-correlation of `a` and `v`.
750
751    See Also
752    --------
753    convolve : Discrete, linear convolution of two one-dimensional sequences.
754    scipy.signal.correlate : uses FFT which has superior performance
755        on large arrays.
756
757    Notes
758    -----
759    The definition of correlation above is not unique and sometimes
760    correlation may be defined differently. Another common definition is [1]_:
761
762    .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}
763
764    which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
765
766    `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5)
767    because it does not use the FFT to compute the convolution; in that case,
768    `scipy.signal.correlate` might be preferable.
769
770    References
771    ----------
772    .. [1] Wikipedia, "Cross-correlation",
773           https://en.wikipedia.org/wiki/Cross-correlation
774
775    Examples
776    --------
777    >>> import numpy as np
778    >>> np.correlate([1, 2, 3], [0, 1, 0.5])
779    array([3.5])
780    >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
781    array([2. ,  3.5,  3. ])
782    >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
783    array([0.5,  2. ,  3.5,  3. ,  0. ])
784
785    Using complex sequences:
786
787    >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
788    array([ 0.5-0.5j,  1.0+0.j ,  1.5-1.5j,  3.0-1.j ,  0.0+0.j ])
789
790    Note that you get the time reversed, complex conjugated result
791    (:math:`\overline{c_{-k}}`) when the two input sequences a and v change
792    places:
793
794    >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
795    array([ 0.0+0.j ,  3.0+1.j ,  1.5+1.5j,  1.0+0.j ,  0.5+0.5j])
796
797    """
798    return multiarray.correlate2(a, v, mode)
799
800
801def _convolve_dispatcher(a, v, mode=None):
802    return (a, v)
803
804
805@array_function_dispatch(_convolve_dispatcher)
806def convolve(a, v, mode='full'):
807    """
808    Returns the discrete, linear convolution of two one-dimensional sequences.
809
810    The convolution operator is often seen in signal processing, where it
811    models the effect of a linear time-invariant system on a signal [1]_.  In
812    probability theory, the sum of two independent random variables is
813    distributed according to the convolution of their individual
814    distributions.
815
816    If `v` is longer than `a`, the arrays are swapped before computation.
817
818    Parameters
819    ----------
820    a : (N,) array_like
821        First one-dimensional input array.
822    v : (M,) array_like
823        Second one-dimensional input array.
824    mode : {'full', 'valid', 'same'}, optional
825        'full':
826          By default, mode is 'full'.  This returns the convolution
827          at each point of overlap, with an output shape of (N+M-1,). At
828          the end-points of the convolution, the signals do not overlap
829          completely, and boundary effects may be seen.
830
831        'same':
832          Mode 'same' returns output of length ``max(M, N)``.  Boundary
833          effects are still visible.
834
835        'valid':
836          Mode 'valid' returns output of length
837          ``max(M, N) - min(M, N) + 1``.  The convolution product is only given
838          for points where the signals overlap completely.  Values outside
839          the signal boundary have no effect.
840
841    Returns
842    -------
843    out : ndarray
844        Discrete, linear convolution of `a` and `v`.
845
846    See Also
847    --------
848    scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
849                               Transform.
850    scipy.linalg.toeplitz : Used to construct the convolution operator.
851    polymul : Polynomial multiplication. Same output as convolve, but also
852              accepts poly1d objects as input.
853
854    Notes
855    -----
856    The discrete convolution operation is defined as
857
858    .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m}
859
860    It can be shown that a convolution :math:`x(t) * y(t)` in time/space
861    is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
862    domain, after appropriate padding (padding is necessary to prevent
863    circular convolution).  Since multiplication is more efficient (faster)
864    than convolution, the function `scipy.signal.fftconvolve` exploits the
865    FFT to calculate the convolution of large data-sets.
866
867    References
868    ----------
869    .. [1] Wikipedia, "Convolution",
870        https://en.wikipedia.org/wiki/Convolution
871
872    Examples
873    --------
874    Note how the convolution operator flips the second array
875    before "sliding" the two across one another:
876
877    >>> import numpy as np
878    >>> np.convolve([1, 2, 3], [0, 1, 0.5])
879    array([0. , 1. , 2.5, 4. , 1.5])
880
881    Only return the middle values of the convolution.
882    Contains boundary effects, where zeros are taken
883    into account:
884
885    >>> np.convolve([1,2,3],[0,1,0.5], 'same')
886    array([1. ,  2.5,  4. ])
887
888    The two arrays are of the same length, so there
889    is only one position where they completely overlap:
890
891    >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
892    array([2.5])
893
894    """
895    a, v = array(a, copy=None, ndmin=1), array(v, copy=None, ndmin=1)
896    if len(a) == 0:
897        raise ValueError('a cannot be empty')
898    if len(v) == 0:
899        raise ValueError('v cannot be empty')
900    if len(v) > len(a):
901        a, v = v, a
902    return multiarray.correlate(a, v[::-1], mode)
903
904
905def _outer_dispatcher(a, b, out=None):
906    return (a, b, out)
907
908
909@array_function_dispatch(_outer_dispatcher)
910def outer(a, b, out=None):
911    """
912    Compute the outer product of two vectors.
913
914    Given two vectors `a` and `b` of length ``M`` and ``N``, respectively,
915    the outer product [1]_ is::
916
917      [[a_0*b_0  a_0*b_1 ... a_0*b_{N-1} ]
918       [a_1*b_0    .
919       [ ...          .
920       [a_{M-1}*b_0            a_{M-1}*b_{N-1} ]]
921
922    Parameters
923    ----------
924    a : (M,) array_like
925        First input vector.  Input is flattened if
926        not already 1-dimensional.
927    b : (N,) array_like
928        Second input vector.  Input is flattened if
929        not already 1-dimensional.
930    out : (M, N) ndarray, optional
931        A location where the result is stored
932
933    Returns
934    -------
935    out : (M, N) ndarray
936        ``out[i, j] = a[i] * b[j]``
937
938    See also
939    --------
940    inner
941    einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
942    ufunc.outer : A generalization to dimensions other than 1D and other
943                  operations. ``np.multiply.outer(a.ravel(), b.ravel())``
944                  is the equivalent.
945    linalg.outer : An Array API compatible variation of ``np.outer``,
946                   which accepts 1-dimensional inputs only.
947    tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
948                is the equivalent.
949
950    References
951    ----------
952    .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
953           ed., Baltimore, MD, Johns Hopkins University Press, 1996,
954           pg. 8.
955
956    Examples
957    --------
958    Make a (*very* coarse) grid for computing a Mandelbrot set:
959
960    >>> import numpy as np
961    >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
962    >>> rl
963    array([[-2., -1.,  0.,  1.,  2.],
964           [-2., -1.,  0.,  1.,  2.],
965           [-2., -1.,  0.,  1.,  2.],
966           [-2., -1.,  0.,  1.,  2.],
967           [-2., -1.,  0.,  1.,  2.]])
968    >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
969    >>> im
970    array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
971           [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
972           [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
973           [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
974           [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
975    >>> grid = rl + im
976    >>> grid
977    array([[-2.+2.j, -1.+2.j,  0.+2.j,  1.+2.j,  2.+2.j],
978           [-2.+1.j, -1.+1.j,  0.+1.j,  1.+1.j,  2.+1.j],
979           [-2.+0.j, -1.+0.j,  0.+0.j,  1.+0.j,  2.+0.j],
980           [-2.-1.j, -1.-1.j,  0.-1.j,  1.-1.j,  2.-1.j],
981           [-2.-2.j, -1.-2.j,  0.-2.j,  1.-2.j,  2.-2.j]])
982
983    An example using a "vector" of letters:
984
985    >>> x = np.array(['a', 'b', 'c'], dtype=object)
986    >>> np.outer(x, [1, 2, 3])
987    array([['a', 'aa', 'aaa'],
988           ['b', 'bb', 'bbb'],
989           ['c', 'cc', 'ccc']], dtype=object)
990
991    """
992    a = asarray(a)
993    b = asarray(b)
994    return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
995
996
997def _tensordot_dispatcher(a, b, axes=None):
998    return (a, b)
999
1000
1001@array_function_dispatch(_tensordot_dispatcher)
1002def tensordot(a, b, axes=2):
1003    """
1004    Compute tensor dot product along specified axes.
1005
1006    Given two tensors, `a` and `b`, and an array_like object containing
1007    two array_like objects, ``(a_axes, b_axes)``, sum the products of
1008    `a`'s and `b`'s elements (components) over the axes specified by
1009    ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
1010    integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
1011    of `a` and the first ``N`` dimensions of `b` are summed over.
1012
1013    Parameters
1014    ----------
1015    a, b : array_like
1016        Tensors to "dot".
1017
1018    axes : int or (2,) array_like
1019        * integer_like
1020          If an int N, sum over the last N axes of `a` and the first N axes
1021          of `b` in order. The sizes of the corresponding axes must match.
1022        * (2,) array_like
1023          Or, a list of axes to be summed over, first sequence applying to `a`,
1024          second to `b`. Both elements array_like must be of the same length.
1025          Each axis may appear at most once; repeated axes are not allowed.
1026          For example, ``axes=([1, 1], [0, 0])`` is invalid.
1027    Returns
1028    -------
1029    output : ndarray
1030        The tensor dot product of the input.
1031
1032    See Also
1033    --------
1034    dot, einsum
1035
1036    Notes
1037    -----
1038    Three common use cases are:
1039        * ``axes = 0`` : tensor product :math:`a\\otimes b`
1040        * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
1041        * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
1042
1043    When `axes` is integer_like, the sequence of axes for evaluation
1044    will be: from the -Nth axis to the -1th axis in `a`,
1045    and from the 0th axis to (N-1)th axis in `b`.
1046    For example, ``axes = 2`` is the equal to
1047    ``axes = [[-2, -1], [0, 1]]``.
1048    When N-1 is smaller than 0, or when -N is larger than -1,
1049    the element of `a` and `b` are defined as the `axes`.
1050
1051    When there is more than one axis to sum over - and they are not the last
1052    (first) axes of `a` (`b`) - the argument `axes` should consist of
1053    two sequences of the same length, with the first axis to sum over given
1054    first in both sequences, the second axis second, and so forth.
1055    The calculation can be referred to ``numpy.einsum``.
1056
1057    For example, if ``a.shape == (2, 3, 4)`` and ``b.shape == (3, 4, 5)``,
1058    then ``axes=([1, 2], [0, 1])`` sums over the ``(3, 4)`` dimensions of
1059    both arrays and produces an output of shape ``(2, 5)``.
1060
1061    Each summation axis corresponds to a distinct contraction index; repeating
1062    an axis (for example ``axes=([1, 1], [0, 0])``) is invalid.
1063
1064    The shape of the result consists of the non-contracted axes of the
1065    first tensor, followed by the non-contracted axes of the second.
1066
1067    Examples
1068    --------
1069    An example on integer_like:
1070
1071    >>> a_0 = np.array([[1, 2], [3, 4]])
1072    >>> b_0 = np.array([[5, 6], [7, 8]])
1073    >>> c_0 = np.tensordot(a_0, b_0, axes=0)
1074    >>> c_0.shape
1075    (2, 2, 2, 2)
1076    >>> c_0
1077    array([[[[ 5,  6],
1078             [ 7,  8]],
1079            [[10, 12],
1080             [14, 16]]],
1081           [[[15, 18],
1082             [21, 24]],
1083            [[20, 24],
1084             [28, 32]]]])
1085
1086    An example on array_like:
1087
1088    >>> a = np.arange(60.).reshape(3,4,5)
1089    >>> b = np.arange(24.).reshape(4,3,2)
1090    >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
1091    >>> c.shape
1092    (5, 2)
1093    >>> c
1094    array([[4400., 4730.],
1095           [4532., 4874.],
1096           [4664., 5018.],
1097           [4796., 5162.],
1098           [4928., 5306.]])
1099
1100    A slower but equivalent way of computing the same...
1101
1102    >>> d = np.zeros((5,2))
1103    >>> for i in range(5):
1104    ...   for j in range(2):
1105    ...     for k in range(3):
1106    ...       for n in range(4):
1107    ...         d[i,j] += a[k,n,i] * b[n,k,j]
1108    >>> c == d
1109    array([[ True,  True],
1110           [ True,  True],
1111           [ True,  True],
1112           [ True,  True],
1113           [ True,  True]])
1114
1115    An extended example taking advantage of the overloading of + and \\*:
1116
1117    >>> a = np.array(range(1, 9)).reshape((2, 2, 2))
1118    >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
1119    >>> A = A.reshape((2, 2))
1120    >>> a; A
1121    array([[[1, 2],
1122            [3, 4]],
1123           [[5, 6],
1124            [7, 8]]])
1125    array([['a', 'b'],
1126           ['c', 'd']], dtype=object)
1127
1128    >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
1129    array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
1130
1131    >>> np.tensordot(a, A, 1)
1132    array([[['acc', 'bdd'],
1133            ['aaacccc', 'bbbdddd']],
1134           [['aaaaacccccc', 'bbbbbdddddd'],
1135            ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
1136
1137    >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
1138    array([[[[['a', 'b'],
1139              ['c', 'd']],
1140              ...
1141
1142    >>> np.tensordot(a, A, (0, 1))
1143    array([[['abbbbb', 'cddddd'],
1144            ['aabbbbbb', 'ccdddddd']],
1145           [['aaabbbbbbb', 'cccddddddd'],
1146            ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
1147
1148    >>> np.tensordot(a, A, (2, 1))
1149    array([[['abb', 'cdd'],
1150            ['aaabbbb', 'cccdddd']],
1151           [['aaaaabbbbbb', 'cccccdddddd'],
1152            ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
1153
1154    >>> np.tensordot(a, A, ((0, 1), (0, 1)))
1155    array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
1156
1157    >>> np.tensordot(a, A, ((2, 1), (1, 0)))
1158    array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
1159
1160    """
1161    try:
1162        iter(axes)
1163    except Exception:
1164        axes_a = list(range(-axes, 0))
1165        axes_b = list(range(axes))
1166    else:
1167        axes_a, axes_b = axes
1168    try:
1169        na = len(axes_a)
1170        axes_a = list(axes_a)
1171    except TypeError:
1172        axes_a = [axes_a]
1173        na = 1
1174    try:
1175        nb = len(axes_b)
1176        axes_b = list(axes_b)
1177    except TypeError:
1178        axes_b = [axes_b]
1179        nb = 1
1180
1181    if len(set(axes_a)) != len(axes_a):
1182        raise ValueError("duplicate axes are not allowed in tensordot")
1183    if len(set(axes_b)) != len(axes_b):
1184        raise ValueError("duplicate axes are not allowed in tensordot")
1185
1186    a, b = asarray(a), asarray(b)
1187    as_ = a.shape
1188    nda = a.ndim
1189    bs = b.shape
1190    ndb = b.ndim
1191    equal = True
1192    if na != nb:
1193        equal = False
1194    else:
1195        for k in range(na):
1196            if as_[axes_a[k]] != bs[axes_b[k]]:
1197                equal = False
1198                break
1199            if axes_a[k] < 0:
1200                axes_a[k] += nda

Showing the first 1,200 of 2772 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai