Beispiel #1
0
def kroneckerproduct(a,b):
    '''Computes a otimes b where otimes is the Kronecker product operator.
    
    Note: the Kronecker product is also known as the matrix direct product
    or tensor product.  It is defined as follows for 2D arrays a and b
    where shape(a)=(m,n) and shape(b)=(p,q):
    c = a otimes b  => cij = a[i,j]*b  where cij is the ij-th submatrix of c.
    So shape(c)=(m*p,n*q).
    
    >>> print kroneckerproduct([[1,2]],[[3],[4]])
    [[3 6]
    [4 8]]
    >>> print kroneckerproduct([[1,2]],[[3,4]])
    [ [3 4 6 8]]
    >>> print kroneckerproduct([[1],[2]],[[3],[4]])
    [[3]
    [4]
    [6]
    [8]]
    '''
    a, b = _na.asarray(a), _na.asarray(b)
    if not (len(a.shape)==2 and len(b.shape)==2):
        raise ValueError, 'Input must be 2D arrays.'
    if not a.iscontiguous():
        a = _gen.reshape(a, a.shape)
    if not b.iscontiguous():
        b = _gen.reshape(b, b.shape)
    o = outerproduct(a,b)
    o.shape = a.shape + b.shape
    return _gen.concatenate(_gen.concatenate(o, axis=1), axis=1)
Beispiel #2
0
def kroneckerproduct(a, b):
    '''Computes a otimes b where otimes is the Kronecker product operator.
    
    Note: the Kronecker product is also known as the matrix direct product
    or tensor product.  It is defined as follows for 2D arrays a and b
    where shape(a)=(m,n) and shape(b)=(p,q):
    c = a otimes b  => cij = a[i,j]*b  where cij is the ij-th submatrix of c.
    So shape(c)=(m*p,n*q).
    
    >>> print kroneckerproduct([[1,2]],[[3],[4]])
    [[3 6]
    [4 8]]
    >>> print kroneckerproduct([[1,2]],[[3,4]])
    [ [3 4 6 8]]
    >>> print kroneckerproduct([[1],[2]],[[3],[4]])
    [[3]
    [4]
    [6]
    [8]]
    '''
    a, b = _na.asarray(a), _na.asarray(b)
    if not (len(a.shape) == 2 and len(b.shape) == 2):
        raise ValueError, 'Input must be 2D arrays.'
    if not a.iscontiguous():
        a = _gen.reshape(a, a.shape)
    if not b.iscontiguous():
        b = _gen.reshape(b, b.shape)
    o = outerproduct(a, b)
    o.shape = a.shape + b.shape
    return _gen.concatenate(_gen.concatenate(o, axis=1), axis=1)
Beispiel #3
0
def outerproduct(array1, array2):
    """outerproduct(array1, array2) computes the NxM outerproduct of N vector
    'array1' and M vector 'array2', where result[i,j] = array1[i]*array2[j].
    """
    array1=_gen.reshape(
        _na.asarray(array1), (-1,1))  # ravel array1 into an Nx1
    array2=_gen.reshape(
        _na.asarray(array2), (1,-1))  # ravel array2 into a 1xM
    return matrixmultiply(array1,array2)   # return NxM result
Beispiel #4
0
def outerproduct(array1, array2):
    """outerproduct(array1, array2) computes the NxM outerproduct of N vector
    'array1' and M vector 'array2', where result[i,j] = array1[i]*array2[j].
    """
    array1 = _gen.reshape(_na.asarray(array1),
                          (-1, 1))  # ravel array1 into an Nx1
    array2 = _gen.reshape(_na.asarray(array2),
                          (1, -1))  # ravel array2 into a 1xM
    return matrixmultiply(array1, array2)  # return NxM result
Beispiel #5
0
def tensormultiply(array1, array2):
    """tensormultiply returns the product for any rank >=1 arrays, defined as:

    r_{xxx, yyy} = \sum_k array1_{xxx, k} array2_{k, yyyy}

    where xxx, yyy denote the rest of the a and b dimensions.
    """
    array1, array2 = _na.asarray(array1), _na.asarray(array2)
    if array1.shape[-1] != array2.shape[0]:
        raise ValueError, "Unmatched dimensions"
    shape = array1.shape[:-1] + array2.shape[1:]
    return _gen.reshape(dot(_gen.reshape(array1, (-1, array1.shape[-1])),
                            _gen.reshape(array2, (array2.shape[0], -1))), shape)
Beispiel #6
0
def tensormultiply(array1, array2):
    """tensormultiply returns the product for any rank >=1 arrays, defined as:

    r_{xxx, yyy} = \sum_k array1_{xxx, k} array2_{k, yyyy}

    where xxx, yyy denote the rest of the a and b dimensions.
    """
    array1, array2 = _na.asarray(array1), _na.asarray(array2)
    if array1.shape[-1] != array2.shape[0]:
        raise ValueError, "Unmatched dimensions"
    shape = array1.shape[:-1] + array2.shape[1:]
    return _gen.reshape(
        dot(_gen.reshape(array1, (-1, array1.shape[-1])),
            _gen.reshape(array2, (array2.shape[0], -1))), shape)
Beispiel #7
0
def num2char(n, format, itemsize=32):
    """num2char formats NumArray 'num' into a CharArray using 'format'

    >>> num2char(_na.arange(0.0,5), '%2.2f')
    CharArray(['0.00', '1.00', '2.00', '3.00', '4.00'])
    >>> num2char(_na.arange(0.0,5), '%d')
    CharArray(['0', '1', '2', '3', '4'])
    >>> num2char(_na.arange(5), "%02d")
    CharArray(['00', '01', '02', '03', '04'])

    Limitations:
    
    1. When formatted values are too large to fit into strings of
    length itemsize, the values are truncated, possibly losing
    significant information.

    2. Complex numbers are not supported.
    
    """
    n = _na.asarray(n)

    if isinstance(n.type(), _nt.ComplexType):
        raise NotImplementedError("num2char doesn't support complex types yet.")
    if n.type() == _na.Float64:
        wnum = n
    else:
        wnum = n.astype(_na.Float64)
    char = CharArray(shape=n.getshape(), itemsize=itemsize)
    _chararray.Format(format, wnum, char)
    return char
Beispiel #8
0
def num2char(n, format, itemsize=32):
    """num2char formats NumArray 'num' into a CharArray using 'format'

    >>> num2char(_na.arange(0.0,5), '%2.2f')
    CharArray(['0.00', '1.00', '2.00', '3.00', '4.00'])
    >>> num2char(_na.arange(0.0,5), '%d')
    CharArray(['0', '1', '2', '3', '4'])
    >>> num2char(_na.arange(5), "%02d")
    CharArray(['00', '01', '02', '03', '04'])

    Limitations:
    
    1. When formatted values are too large to fit into strings of
    length itemsize, the values are truncated, possibly losing
    significant information.

    2. Complex numbers are not supported.
    
    """
    n = _na.asarray(n)

    if isinstance(n.type(), _nt.ComplexType):
        raise NotImplementedError(
            "num2char doesn't support complex types yet.")
    if n.type() == _na.Float64:
        wnum = n
    else:
        wnum = n.astype(_na.Float64)
    char = CharArray(shape=n.getshape(), itemsize=itemsize)
    _chararray.Format(format, wnum, char)
    return char
Beispiel #9
0
def mask(a, m):
    """mask(a, m) returns the values of 'a' satisfying category 'm'.
    mask does a parallel check for values which are not classifyable
    by the categorization code, raising a RuntimeError exception if
    any are found.
    """
    a = _na.asarray(a)
    if isinstance(a.type(), _na.IntegralType):
        a = a.astype('Float64')
    if isinstance(a.type(), _na.ComplexType):
        f = _na.ieeemask(a.real, m) | _na.ieeemask(a.imag, m)
        g = _na.ieeemask(a.real, BUG) | _na.ieeemask(a.imag, BUG)
    else:
        f = _na.ieeemask(a, m)
        g = _na.ieeemask(a, BUG)
    if _na.bitwise_or.reduce(_na.ravel(g)) != 0:
        raise RuntimeError("Unclassifyable floating point values.")
    if f.rank == 0:
        f = f[()]
    return f
Beispiel #10
0
def mask(a, m):
    """mask(a, m) returns the values of 'a' satisfying category 'm'.
    mask does a parallel check for values which are not classifyable
    by the categorization code, raising a RuntimeError exception if
    any are found.
    """
    a = _na.asarray(a)
    if isinstance(a.type(), _na.IntegralType):
        a = a.astype('Float64')
    if isinstance(a.type(), _na.ComplexType):
        f = _na.ieeemask(a.real, m) | _na.ieeemask(a.imag, m)
        g = _na.ieeemask(a.real, BUG) | _na.ieeemask(a.imag, BUG)
    else:
        f = _na.ieeemask(a, m)
        g = _na.ieeemask(a, BUG)
    if _na.bitwise_or.reduce(_na.ravel(g)) != 0:
        raise RuntimeError("Unclassifyable floating point values.")
    if f.rank == 0:
        f = f[()]
    return f