Пример #1
0
def matmul(a, b, no_blas=False):
    """
    Matrix multiplication of two 2-D arrays.

    Parameters
    ----------
    a : array_like
        First argument.
    b : array_like
        Second argument.

    Returns
    -------
    output : ndarray
        Returns the matrix multiplication of `a` and `b`.

    Raises
    ------
    ValueError
        If the last dimension of `a` is not the same size as
        the second-to-last dimension of `b`.

    See Also
    --------
    dot : Dot product of two arrays.

    Examples
    --------
    >>> np.matmul(np.array([[1,2],[3,4]]),np.array([[5,6],[7,8]]))
    array([[19, 22],
           [43, 50]])
    """
    if not dtype_equal(a, b):
        raise ValueError("Input must be of same type")

    if a.ndim != 2 and b.ndim != 2:
        raise ValueError("Input must be 2-D.")

    if not (bhary.check(a) or bhary.check(b)):  # Both are regular numpy arrays
        return numpy.dot(a, b)
    else:
        a = array_create.array(a)
        b = array_create.array(b)

    # If the dtypes are both float, we can use BLAS to calculate
    # the dot-product, if BLAS is present.
    if not no_blas and a.dtype.kind in np.typecodes[
            "AllFloat"] and b.dtype.kind in np.typecodes["AllFloat"]:
        try:
            return blas.gemm(a, b)
        except:
            pass

    return ufuncs.add.reduce(a[:, numpy.newaxis] * numpy.transpose(b), -1)
Пример #2
0
def matmul(a, b, no_blas=False):
    """
    Matrix multiplication of two 2-D arrays.

    Parameters
    ----------
    a : array_like
        First argument.
    b : array_like
        Second argument.

    Returns
    -------
    output : ndarray
        Returns the matrix multiplication of `a` and `b`.

    Raises
    ------
    ValueError
        If the last dimension of `a` is not the same size as
        the second-to-last dimension of `b`.

    See Also
    --------
    dot : Dot product of two arrays.

    Examples
    --------
    >>> np.matmul(np.array([[1,2],[3,4]]),np.array([[5,6],[7,8]]))
    array([[19, 22],
           [43, 50]])
    """
    if not dtype_equal(a, b):
        raise ValueError("Input must be of same type")

    if a.ndim != 2 and b.ndim != 2:
        raise ValueError("Input must be 2-D.")

    if not (bhary.check(a) or bhary.check(b)):  # Both are regular numpy arrays
        return numpy.dot(a, b)
    else:
        a = array_create.array(a)
        b = array_create.array(b)

    # If the dtypes are both float, we can use BLAS to calculate
    # the dot-product, if BLAS is present.
    if not no_blas and a.dtype.kind in np.typecodes["AllFloat"] and b.dtype.kind in np.typecodes["AllFloat"]:
        try:
            return blas.gemm(a, b)
        except:
            pass

    return ufuncs.add.reduce(a[:, numpy.newaxis] * numpy.transpose(b), -1)
Пример #3
0
def flatten(ary, order='C', always_copy=True):
    """
    Return a copy of the array collapsed into one dimension.

    Parameters
    ----------
    ary : array_like
        Array from which to retrieve the flattened data from.
    order : {'C', 'F', 'A', 'K'}, optional
        'C' means to flatten in row-major (C-style) order.
        'F' means to flatten in column-major (Fortran-
        style) order. 'A' means to flatten in column-major
        order if `a` is Fortran *contiguous* in memory,
        row-major order otherwise. 'K' means to flatten
        `a` in the order the elements occur in memory.
        The default is 'C'.
    always_copy : boolean
        When False, a copy is only made when necessary

    Returns
    -------
    y : ndarray
        A copy of the input array, flattened to one dimension.

    Notes
    -----
    The order of the data in memory is always row-major (C-style).

    Examples
    --------
    >>> a = np.array([[1,2], [3,4]])
    >>> np.flatten(a)
    array([1, 2, 3, 4])
    """

    if order == 'F' or (order == 'A' and not ary.flags['F_CONTIGUOUS']):
        ary = numpy.transpose(ary)

    ret = ary.reshape(_util.totalsize(ary))
    if always_copy:
        return ret.copy()
    else:
        return ret
Пример #4
0
def flatten(ary, order='C', always_copy=True):
    """
    Return a copy of the array collapsed into one dimension.

    Parameters
    ----------
    ary : array_like
        Array from which to retrieve the flattened data from.
    order : {'C', 'F', 'A', 'K'}, optional
        'C' means to flatten in row-major (C-style) order.
        'F' means to flatten in column-major (Fortran-
        style) order. 'A' means to flatten in column-major
        order if `a` is Fortran *contiguous* in memory,
        row-major order otherwise. 'K' means to flatten
        `a` in the order the elements occur in memory.
        The default is 'C'.
    always_copy : boolean
        When False, a copy is only made when necessary

    Returns
    -------
    y : ndarray
        A copy of the input array, flattened to one dimension.

    Notes
    -----
    The order of the data in memory is always row-major (C-style).

    Examples
    --------
    >>> a = np.array([[1,2], [3,4]])
    >>> np.flatten(a)
    array([1, 2, 3, 4])
    """

    if order == 'F' or (order == 'A' and not ary.flags['F_CONTIGUOUS']):
        ary = numpy.transpose(ary)

    ret = ary.reshape(_util.totalsize(ary))
    if always_copy:
        return ret.copy()
    else:
        return ret
Пример #5
0
def dot(a,b, no_matmul=False):
    """
    Dot product of two arrays.

    For 2-D arrays it is equivalent to matrix multiplication, and for 1-D
    arrays to inner product of vectors (without complex conjugation). For
    N dimensions it is a sum product over the last axis of `a` and
    the second-to-last of `b`::

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

    Parameters
    ----------
    a : array_like
        First argument.
    b : array_like
        Second argument.

    Returns
    -------
    output : ndarray
        Returns the dot product of `a` and `b`.  If `a` and `b` are both
        scalars or both 1-D arrays then a scalar is returned; otherwise
        an array is returned.

    Raises
    ------
    ValueError
        If the last dimension of `a` is not the same size as
        the second-to-last dimension of `b`.

    See Also
    --------
    vdot : Complex-conjugating dot product.
    tensordot : Sum products over arbitrary axes.
    einsum : Einstein summation convention.

    Examples
    --------
    >>> np.dot(3, 4)
    12

    Neither argument is complex-conjugated:

    >>> np.dot([2j, 3j], [2j, 3j])
    (-13+0j)

    For 2-D arrays it's the matrix product:

    >>> a = [[1, 0], [0, 1]]
    >>> b = [[4, 1], [2, 2]]
    >>> np.dot(a, b)
    array([[4, 1],
           [2, 2]])

    >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
    >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
    >>> np.dot(a, b)[2,3,2,1,2,2]
    499128
    >>> sum(a[2,3,2,:] * b[1,2,:,2])
    499128

    """
    if ndarray.check(a) or ndarray.check(b):
        a = array_create.array(a)
        b = array_create.array(b)
    if b.ndim == 1:
        return ufunc.add.reduce(a*b,-1)
    if a.ndim == 1:
        return ufunc.add.reduce(a*numpy.transpose(b),-1)
    if (not no_matmul) and a.ndim == 2 and b.ndim == 2:
        return matmul(a,b)
    return ufunc.add.reduce(a[:,numpy.newaxis]*numpy.transpose(b),-1)
Пример #6
0
def dot(a, b, no_blas=False):
    """
    Dot product of two arrays.

    For 2-D arrays it is equivalent to matrix multiplication, and for 1-D
    arrays to inner product of vectors (without complex conjugation). For
    N dimensions it is a sum product over the last axis of `a` and
    the second-to-last of `b`::

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

    Parameters
    ----------
    a : array_like
        First argument.
    b : array_like
        Second argument.

    Returns
    -------
    output : ndarray
        Returns the dot product of `a` and `b`.  If `a` and `b` are both
        scalars or both 1-D arrays then a scalar is returned; otherwise
        an array is returned.

    Raises
    ------
    ValueError
        If the last dimension of `a` is not the same size as
        the second-to-last dimension of `b`.

    See Also
    --------
    vdot : Complex-conjugating dot product.
    tensordot : Sum products over arbitrary axes.
    einsum : Einstein summation convention.

    Examples
    --------
    >>> np.dot(3, 4)
    12

    Neither argument is complex-conjugated:

    >>> np.dot([2j, 3j], [2j, 3j])
    (-13+0j)

    For 2-D arrays it's the matrix product:

    >>> a = [[1, 0], [0, 1]]
    >>> b = [[4, 1], [2, 2]]
    >>> np.dot(a, b)
    array([[4, 1],
           [2, 2]])

    >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
    >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
    >>> np.dot(a, b)[2,3,2,1,2,2]
    499128
    >>> sum(a[2,3,2,:] * b[1,2,:,2])
    499128

    """
    if not (bhary.check(a) or bhary.check(b)):  # Both are regular numpy arrays
        return numpy.dot(a, b)
    else:
        a = array_create.array(a)
        b = array_create.array(b)

    if b.ndim == 1:
        return ufuncs.add.reduce(a * b, -1)

    if a.ndim == 1:
        return ufuncs.add.reduce(a * numpy.transpose(b), -1)

    if not no_blas and a.ndim == 2 and b.ndim == 2:
        # If the dtypes are both float, we can use BLAS to calculate
        # the dot-product, if BLAS is present.
        if a.dtype.kind in np.typecodes[
                "AllFloat"] and b.dtype.kind in np.typecodes["AllFloat"]:
            try:
                return blas.gemm(a, b)
            except:
                pass

    return ufuncs.add.reduce(a[:, numpy.newaxis] * numpy.transpose(b), -1)