Пример #1
0
def frame_constant(a, shape, cval=0):
    """frame_nearest creates an oversized copy of 'a' with new 'shape'
    and the contents of 'a' in the center.  The boundary pixels are
    copied from the nearest edge pixel in 'a'.

    >>> a = num.arange(16, shape=(4,4))
    >>> frame_constant(a, (8,8), cval=42)
    array([[42, 42, 42, 42, 42, 42, 42, 42],
           [42, 42, 42, 42, 42, 42, 42, 42],
           [42, 42,  0,  1,  2,  3, 42, 42],
           [42, 42,  4,  5,  6,  7, 42, 42],
           [42, 42,  8,  9, 10, 11, 42, 42],
           [42, 42, 12, 13, 14, 15, 42, 42],
           [42, 42, 42, 42, 42, 42, 42, 42],
           [42, 42, 42, 42, 42, 42, 42, 42]])

    """

    b = num.zeros(shape, typecode=a.type())
    delta = (num.array(b.shape) - num.array(a.shape))
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = a.shape[0] + dy
    mx = a.shape[1] + dx

    b[dy:my, dx:mx] = a  # center
    b[:dy, dx:mx] = cval  # top
    b[my:, dx:mx] = cval  # bottom
    b[dy:my, :dx] = cval  # left
    b[dy:my, mx:] = cval  # right
    b[:dy, :dx] = cval  # topleft
    b[:dy, mx:] = cval  # topright
    b[my:, :dx] = cval  # bottomleft
    b[my:, mx:] = cval  # bottomright
    return b
Пример #2
0
def _broadcast_arguments(args, shape):
    """If there are no arrays/sequences in the args tuple, return args
    and shape unchanged. Otherwise: if shape is empty, broadcast all
    arrays/sequences in the arguments to a common shape, and return
    the result together with the broadcasted shape. If shape is not
    empty, broadcast all arrays/sequences in the arguments to the
    given shape and return these together with the unchanged
    shape. Scalar arguments are never changed.
    """
    if isinstance(shape, _types.IntType):
        shape = [shape]
    array_args = []
    for arg in args:
        if (isinstance(arg, num.ArrayType) or isinstance(arg, _types.ListType)
                or isinstance(arg, _types.TupleType)):
            array_args.append(num.array(arg))
    if len(array_args) > 0:
        if len(shape) == 0:
            array_args = _gen._nWayBroadcast(array_args)
            shape = array_args[0].shape
        else:
            for ii in range(len(array_args)):
                array_args[ii] = _gen._broadcast(num.array(array_args[ii]),
                                                 shape)
        new_args = []
        for arg in args:
            if (isinstance(arg, num.ArrayType)
                    or isinstance(arg, _types.ListType)
                    or isinstance(arg, _types.TupleType)):
                new_args.append(array_args.pop(0))
            else:
                new_args.append(arg)
            args = tuple(new_args)
    return args, shape
Пример #3
0
def _broadcast_arguments(args, shape):
    """If there are no arrays/sequences in the args tuple, return args
    and shape unchanged. Otherwise: if shape is empty, broadcast all
    arrays/sequences in the arguments to a common shape, and return
    the result together with the broadcasted shape. If shape is not
    empty, broadcast all arrays/sequences in the arguments to the
    given shape and return these together with the unchanged
    shape. Scalar arguments are never changed.
    """
    if isinstance(shape, _types.IntType): 
        shape = [shape]
    array_args = []
    for arg in args:
        if (isinstance(arg, num.ArrayType) or
            isinstance(arg, _types.ListType) or
            isinstance(arg, _types.TupleType)):
            array_args.append(num.array(arg))
    if len(array_args) > 0:
        if len(shape) == 0:
            array_args = _gen._nWayBroadcast(array_args)
            shape = array_args[0].shape
        else:
            for ii in range(len(array_args)):
                array_args[ii] = _gen._broadcast(num.array(array_args[ii]), shape) 
        new_args = []
        for arg in args:
            if (isinstance(arg, num.ArrayType) or
                isinstance(arg, _types.ListType) or
                isinstance(arg, _types.TupleType)):
                new_args.append(array_args.pop(0))
            else:
                new_args.append(arg)
            args = tuple(new_args)
    return args, shape
Пример #4
0
def frame_constant(a, shape, cval=0):
    """frame_nearest creates an oversized copy of 'a' with new 'shape'
    and the contents of 'a' in the center.  The boundary pixels are
    copied from the nearest edge pixel in 'a'.

    >>> a = num.arange(16, shape=(4,4))
    >>> frame_constant(a, (8,8), cval=42)
    array([[42, 42, 42, 42, 42, 42, 42, 42],
           [42, 42, 42, 42, 42, 42, 42, 42],
           [42, 42,  0,  1,  2,  3, 42, 42],
           [42, 42,  4,  5,  6,  7, 42, 42],
           [42, 42,  8,  9, 10, 11, 42, 42],
           [42, 42, 12, 13, 14, 15, 42, 42],
           [42, 42, 42, 42, 42, 42, 42, 42],
           [42, 42, 42, 42, 42, 42, 42, 42]])

    """
    
    b = num.zeros(shape, typecode=a.type())
    delta = (num.array(b.shape) - num.array(a.shape))
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = a.shape[0] + dy
    mx = a.shape[1] + dx
    
    b[dy:my, dx:mx] = a              # center
    b[:dy,dx:mx]  = cval             # top
    b[my:,dx:mx]  = cval             # bottom
    b[dy:my, :dx] = cval             # left
    b[dy:my, mx:] = cval             # right
    b[:dy, :dx]   = cval             # topleft
    b[:dy, mx:]   = cval             # topright
    b[my:, :dx]   = cval             # bottomleft
    b[my:, mx:]   = cval             # bottomright
    return b
Пример #5
0
def unframe(a, shape):
    """unframe extracts the center slice of framed array 'a' which had
    'shape' prior to framing."""

    delta = num.array(a.shape) - num.array(shape)
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = shape[0] + dy
    mx = shape[1] + dx
    return a[dy:my, dx:mx]
Пример #6
0
def unframe(a, shape):

    """unframe extracts the center slice of framed array 'a' which had
    'shape' prior to framing."""

    delta = num.array(a.shape) - num.array(shape)
    dy = delta[0]//2
    dx = delta[1]//2
    my = shape[0] + dy
    mx = shape[1] + dx
    return a[dy:my, dx:mx]
Пример #7
0
def multivariate_normal(mean, cov, shape=[]):
    """multivariate_normal(mean, cov) or multivariate_normal(mean, cov, [m, n, ...])

    Returns an array containing multivariate normally distributed
    random numbers with specified mean and covariance.

    |mean| must be a one-dimensional array. |cov| must be a square
    two-dimensional array with the same number of rows and columns as
    |mean| has elements.

    The first form returns a single 1-D array containing a
    multivariate normal.

    The second form returns an array of shape (m, n, ...,
    cov.getshape()[0]). In this case, output[i,j,...,:] is a 1-D array
    containing a multivariate normal.
    """
    # Check preconditions on arguments
    mean = num.array(mean)
    cov = num.array(cov)
    if len(mean.getshape()) != 1:
        raise ArgumentError, "mean must be 1 dimensional."
    if (len(cov.getshape()) != 2) or (cov.getshape()[0] != cov.getshape()[1]):
        raise ArgumentError, "cov must be 2 dimensional and square."
    if mean.getshape()[0] != cov.getshape()[0]:
        raise ArgumentError, "mean and cov must have same length."
    # Compute shape of output
    if isinstance(shape, _types.IntType): shape = [shape]
    final_shape = list(shape[:])
    final_shape.append(mean.getshape()[0])
    # Create a matrix of independent standard normally distributed random
    # numbers. The matrix has rows with the same length as mean and as
    # many rows are necessary to form a matrix of shape final_shape.
    x = ranlib.standard_normal(num.multiply.reduce(final_shape))
    x.setshape(num.multiply.reduce(final_shape[0:len(final_shape) - 1]),
               mean.getshape()[0])
    # Transform matrix of standard normals into matrix where each row
    # contains multivariate normals with the desired covariance.
    # Compute A such that matrixmultiply(transpose(A),A) == cov.
    # Then the matrix products of the rows of x and A has the desired
    # covariance. Note that sqrt(s)*v where (u,s,v) is the singular value
    # decomposition of cov is such an A.
    (u, s, v) = linalg.singular_value_decomposition(cov)
    x = num.matrixmultiply(x * num.sqrt(s), v)
    # The rows of x now have the correct covariance but mean 0. Add
    # mean to each row. Then each row will have mean mean.
    num.add(mean, x, x)
    x.setshape(final_shape)
    return x
Пример #8
0
def multivariate_normal(mean, cov, shape=[]):
    """multivariate_normal(mean, cov) or multivariate_normal(mean, cov, [m, n, ...])

    Returns an array containing multivariate normally distributed
    random numbers with specified mean and covariance.

    |mean| must be a one-dimensional array. |cov| must be a square
    two-dimensional array with the same number of rows and columns as
    |mean| has elements.

    The first form returns a single 1-D array containing a
    multivariate normal.

    The second form returns an array of shape (m, n, ...,
    cov.getshape()[0]). In this case, output[i,j,...,:] is a 1-D array
    containing a multivariate normal.
    """
    # Check preconditions on arguments
    mean = num.array(mean)
    cov = num.array(cov)
    if len(mean.getshape()) != 1:
        raise ArgumentError, "mean must be 1 dimensional."
    if (len(cov.getshape()) != 2) or (cov.getshape()[0] != cov.getshape()[1]):
        raise ArgumentError, "cov must be 2 dimensional and square."
    if mean.getshape()[0] != cov.getshape()[0]:
        raise ArgumentError, "mean and cov must have same length."
    # Compute shape of output
    if isinstance(shape, _types.IntType): shape = [shape]
    final_shape = list(shape[:])
    final_shape.append(mean.getshape()[0])
    # Create a matrix of independent standard normally distributed random
    # numbers. The matrix has rows with the same length as mean and as
    # many rows are necessary to form a matrix of shape final_shape.
    x = ranlib.standard_normal(num.multiply.reduce(final_shape))
    x.setshape(num.multiply.reduce(final_shape[0:len(final_shape)-1]),
               mean.getshape()[0])
    # Transform matrix of standard normals into matrix where each row
    # contains multivariate normals with the desired covariance.
    # Compute A such that matrixmultiply(transpose(A),A) == cov.
    # Then the matrix products of the rows of x and A has the desired
    # covariance. Note that sqrt(s)*v where (u,s,v) is the singular value
    # decomposition of cov is such an A.
    (u,s,v) = linalg.singular_value_decomposition(cov)
    x = num.matrixmultiply(x*num.sqrt(s),v)
    # The rows of x now have the correct covariance but mean 0. Add
    # mean to each row. Then each row will have mean mean.
    num.add(mean,x,x)
    x.setshape(final_shape)
    return x
Пример #9
0
def multinomial(trials, probs, shape=[]):
    """multinomial(trials, probs) or multinomial(trials, probs, [n, m, ...])

    Returns array of multinomial distributed integer vectors.

    |trials| is the number of trials in each multinomial distribution. 
    |probs| is a one dimensional array. There are len(prob)+1 events. 
    prob[i] is the probability of the i-th event, 0<=i<len(prob). The
    probability of event len(prob) is 1.-num.sum(prob).

    The first form returns a single 1-D array containing one
    multinomially distributed vector.

    The second form returns an array of shape (m, n, ..., len(probs)). 
    In this case, output[i,j,...,:] is a 1-D array containing a
    multinomially distributed integer 1-D array.
    """
    # Check preconditions on arguments
    probs = num.array(probs)
    if len(probs.getshape()) != 1:
        raise ArgumentError, "probs must be 1 dimensional."
        # Compute shape of output
    if type(shape) == type(0): shape = [shape]
    final_shape = shape[:]
    final_shape.append(probs.getshape()[0] + 1)
    x = ranlib.multinomial(trials, probs.astype(num.Float32),
                           num.multiply.reduce(shape))
    # Change its shape to the desire one
    x.setshape(final_shape)
    return x
Пример #10
0
def multinomial(trials, probs, shape=[]):
    """multinomial(trials, probs) or multinomial(trials, probs, [n, m, ...])

    Returns array of multinomial distributed integer vectors.

    |trials| is the number of trials in each multinomial distribution. 
    |probs| is a one dimensional array. There are len(prob)+1 events. 
    prob[i] is the probability of the i-th event, 0<=i<len(prob). The
    probability of event len(prob) is 1.-num.sum(prob).

    The first form returns a single 1-D array containing one
    multinomially distributed vector.

    The second form returns an array of shape (m, n, ..., len(probs)). 
    In this case, output[i,j,...,:] is a 1-D array containing a
    multinomially distributed integer 1-D array.
    """
    # Check preconditions on arguments
    probs = num.array(probs)
    if len(probs.getshape()) != 1:
        raise ArgumentError, "probs must be 1 dimensional."
        # Compute shape of output
    if type(shape) == type(0): shape = [shape]
    final_shape = shape[:]
    final_shape.append(probs.getshape()[0]+1)
    x = ranlib.multinomial(trials, probs.astype(num.Float32),
                           num.multiply.reduce(shape))
    # Change its shape to the desire one
    x.setshape(final_shape)
    return x
Пример #11
0
def _correlate2d_fft(data0, kernel0, output=None, mode="nearest", cval=0.0):
    """_correlate2d_fft does 2d correlation of 'data' with 'kernel', storing
    the result in 'output' using the FFT to perform the correlation.

    supported 'mode's include:
        'nearest'   elements beyond boundary come from nearest edge pixel.
        'wrap'      elements beyond boundary come from the opposite array edge.
        'reflect'   elements beyond boundary come from reflection on same array edge.
        'constant'  elements beyond boundary are set to 'cval' 
    """
    shape = data0.shape
    kshape = kernel0.shape
    oversized = (num.array(shape) + num.array(kshape))

    dy = kshape[0] // 2
    dx = kshape[1] // 2

    kernel = num.zeros(oversized, typecode=num.Float64)
    kernel[:kshape[0], :kshape[1]] = kernel0[::-1, ::
                                             -1]  # convolution <-> correlation
    data = iraf_frame.frame(data0, oversized, mode=mode, cval=cval)

    complex_result = (isinstance(data, _nt.ComplexType)
                      or isinstance(kernel, _nt.ComplexType))

    Fdata = fft.fft2d(data)
    del data

    Fkernel = fft.fft2d(kernel)
    del kernel

    num.multiply(Fdata, Fkernel, Fdata)
    del Fkernel

    if complex_result:
        convolved = fft.inverse_fft2d(Fdata, s=oversized)
    else:
        convolved = fft.inverse_real_fft2d(Fdata, s=oversized)

    result = convolved[kshape[0] - 1:shape[0] + kshape[0] - 1,
                       kshape[1] - 1:shape[1] + kshape[1] - 1]

    if output is not None:
        output._copyFrom(result)
    else:
        return result
Пример #12
0
def _correlate2d_fft(data0, kernel0, output=None, mode="nearest", cval=0.0):
    """_correlate2d_fft does 2d correlation of 'data' with 'kernel', storing
    the result in 'output' using the FFT to perform the correlation.

    supported 'mode's include:
        'nearest'   elements beyond boundary come from nearest edge pixel.
        'wrap'      elements beyond boundary come from the opposite array edge.
        'reflect'   elements beyond boundary come from reflection on same array edge.
        'constant'  elements beyond boundary are set to 'cval' 
    """
    shape = data0.shape
    kshape = kernel0.shape
    oversized = (num.array(shape) + num.array(kshape))

    dy = kshape[0] // 2
    dx = kshape[1] // 2

    kernel = num.zeros(oversized, typecode=num.Float64)
    kernel[:kshape[0], :kshape[1]] = kernel0[::-1,::-1]   # convolution <-> correlation
    data = iraf_frame.frame(data0, oversized, mode=mode, cval=cval)

    complex_result = (isinstance(data, _nt.ComplexType) or 
                      isinstance(kernel, _nt.ComplexType))

    Fdata = fft.fft2d(data)
    del data
    
    Fkernel = fft.fft2d(kernel)
    del kernel
    
    num.multiply(Fdata, Fkernel, Fdata)
    del Fkernel

    if complex_result:
        convolved = fft.inverse_fft2d( Fdata, s=oversized)
    else:
        convolved = fft.inverse_real_fft2d( Fdata, s=oversized)
        
    result = convolved[ kshape[0]-1:shape[0]+kshape[0]-1, kshape[1]-1:shape[1]+kshape[1]-1 ]

    if output is not None:
        output._copyFrom( result )
    else:
        return result
Пример #13
0
def eigenvectors(a):
    """eigenvectors(a) returns u,v  where u is the eigenvalues and
v is a matrix of eigenvectors with vector v[i] corresponds to 
eigenvalue u[i].  Satisfies the equation dot(a, v[i]) = u[i]*v[i]
"""
    _assertRank2(a)
    _assertSquareness(a)
    t =_commonType(a)
    real_t = _array_type[0][_array_precision[t]]
    a = _fastCopyAndTranspose(t, a)
    n = a.getshape()[0]
    dummy = num.zeros((1,), t)
    if _array_kind[t] == 1: # Complex routines take different arguments
        lapack_routine = lapack_lite2.zgeev
        w = num.zeros((n,), t)
        v = num.zeros((n,n), t)
        lwork = 1
        work = num.zeros((lwork,),t)
        rwork = num.zeros((2*n,),real_t)
        results = lapack_routine('N', 'V', n, a, n, w,
                                  dummy, 1, v, n, work, -1, rwork, 0)
        lwork = int(abs(work[0]))
        work = num.zeros((lwork,),t)
        results = lapack_routine('N', 'V', n, a, n, w,
                                  dummy, 1, v, n, work, lwork, rwork, 0)
    else:
        lapack_routine = lapack_lite2.dgeev
        wr = num.zeros((n,), t)
        wi = num.zeros((n,), t)
        vr = num.zeros((n,n), t)
        lwork = 1
        work = num.zeros((lwork,),t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi,
                                  dummy, 1, vr, n, work, -1, 0)
        lwork = int(work[0])
        work = num.zeros((lwork,),t)
        results = lapack_routine('N', 'V', n, a, n, wr, wi,
                                  dummy, 1, vr, n, work, lwork, 0)
        if num.logical_and.reduce(num.equal(wi, 0.)):
            w = wr
            v = vr
        else:
            w = wr+1j*wi
            v = num.array(vr,type=num.Complex)
            ind = num.nonzero(
                          num.equal(
                              num.equal(wi,0.0) # true for real e-vals
                                       ,0)          # true for complex e-vals
                                 )                  # indices of complex e-vals
            for i in range(len(ind)/2):
                v[ind[2*i]] = vr[ind[2*i]] + 1j*vr[ind[2*i+1]]
                v[ind[2*i+1]] = vr[ind[2*i]] - 1j*vr[ind[2*i+1]]
    if results['info'] > 0:
        raise LinAlgError, 'Eigenvalues did not converge'
    return w,v
Пример #14
0
def frame_nearest(a, shape, cval=None):

    """frame_nearest creates an oversized copy of 'a' with new 'shape'
    and the contents of 'a' in the center.  The boundary pixels are
    copied from the nearest edge pixel in 'a'.

    >>> a = num.arange(16, shape=(4,4))
    >>> frame_nearest(a, (8,8))
    array([[ 0,  0,  0,  1,  2,  3,  3,  3],
           [ 0,  0,  0,  1,  2,  3,  3,  3],
           [ 0,  0,  0,  1,  2,  3,  3,  3],
           [ 4,  4,  4,  5,  6,  7,  7,  7],
           [ 8,  8,  8,  9, 10, 11, 11, 11],
           [12, 12, 12, 13, 14, 15, 15, 15],
           [12, 12, 12, 13, 14, 15, 15, 15],
           [12, 12, 12, 13, 14, 15, 15, 15]])
           
    """
    
    b = num.zeros(shape, typecode=a.type())
    delta = (num.array(b.shape) - num.array(a.shape))
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = a.shape[0] + dy
    mx = a.shape[1] + dx
    
    b[dy:my, dx:mx] = a                  # center
    b[:dy,dx:mx]  = a[0:1,:]               # top
    b[my:,dx:mx]  = a[-1:,:]              # bottom
    b[dy:my, :dx] = a[:, 0:1]              # left
    b[dy:my, mx:] = a[:, -1:]             # right
    b[:dy, :dx]   = a[0,0]               # topleft
    b[:dy, mx:]   = a[0,-1]              # topright
    b[my:, :dx]   = a[-1, 0]             # bottomleft
    b[my:, mx:]   = a[-1, -1]            # bottomright
    
    return b
Пример #15
0
def frame_reflect(a, shape, cval=None):

    """frame_reflect creates an oversized copy of 'a' with new 'shape'
    and the contents of 'a' in the center.  The boundary pixels are
    reflected from the nearest edge pixels in 'a'.

    >>> a = num.arange(16, shape=(4,4))
    >>> frame_reflect(a, (8,8))
    array([[ 5,  4,  4,  5,  6,  7,  7,  6],
           [ 1,  0,  0,  1,  2,  3,  3,  2],
           [ 1,  0,  0,  1,  2,  3,  3,  2],
           [ 5,  4,  4,  5,  6,  7,  7,  6],
           [ 9,  8,  8,  9, 10, 11, 11, 10],
           [13, 12, 12, 13, 14, 15, 15, 14],
           [13, 12, 12, 13, 14, 15, 15, 14],
           [ 9,  8,  8,  9, 10, 11, 11, 10]])
    """
    
    b = num.zeros(shape, typecode=a.type())
    delta = (num.array(b.shape) - num.array(a.shape))
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = a.shape[0] + dy
    mx = a.shape[1] + dx
    sy = delta[0] - dy
    sx = delta[1] - dx
    
    b[dy:my, dx:mx] = a                            # center
    b[:dy,dx:mx]  = a[:dy,:][::-1,:]               # top
    b[my:,dx:mx]  = a[-sy:,:][::-1,:]              # bottom
    b[dy:my,:dx]  = a[:,:dx][:,::-1]               # left
    b[dy:my,mx:]  = a[:,-sx:][:,::-1]              # right
    b[:dy,:dx]    = a[:dy,:dx][::-1,::-1]          # topleft
    b[:dy,mx:]    = a[:dy,-sx:][::-1,::-1]         # topright
    b[my:,:dx]    = a[-sy:,:dx][::-1,::-1]         # bottomleft
    b[my:,mx:]    = a[-sy:,-sx:][::-1,::-1]        # bottomright
    return b
Пример #16
0
def frame_wrap(a, shape, cval=None):
    """frame_wrap creates an oversized copy of 'a' with new 'shape'
    and the contents of 'a' in the center.  The boundary pixels are
    wrapped around to the opposite edge pixels in 'a'.

    >>> a = num.arange(16, shape=(4,4))
    >>> frame_wrap(a, (8,8))
    array([[10, 11,  8,  9, 10, 11,  8,  9],
           [14, 15, 12, 13, 14, 15, 12, 13],
           [ 2,  3,  0,  1,  2,  3,  0,  1],
           [ 6,  7,  4,  5,  6,  7,  4,  5],
           [10, 11,  8,  9, 10, 11,  8,  9],
           [14, 15, 12, 13, 14, 15, 12, 13],
           [ 2,  3,  0,  1,  2,  3,  0,  1],
           [ 6,  7,  4,  5,  6,  7,  4,  5]])

    """

    b = num.zeros(shape, typecode=a.type())
    delta = (num.array(b.shape) - num.array(a.shape))
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = a.shape[0] + dy
    mx = a.shape[1] + dx
    sy = delta[0] - dy
    sx = delta[1] - dx

    b[dy:my, dx:mx] = a  # center
    b[:dy, dx:mx] = a[-dy:, :]  # top
    b[my:, dx:mx] = a[:sy, :]  # bottom
    b[dy:my, :dx] = a[:, -dx:]  # left
    b[dy:my, mx:] = a[:, :sx]  # right
    b[:dy, :dx] = a[-dy:, -dx:]  # topleft
    b[:dy, mx:] = a[-dy:, :sx]  # topright
    b[my:, :dx] = a[:sy, -dx:]  # bottomleft
    b[my:, mx:] = a[:sy, :sx]  # bottomright
    return b
Пример #17
0
def frame_wrap(a, shape, cval=None):
    """frame_wrap creates an oversized copy of 'a' with new 'shape'
    and the contents of 'a' in the center.  The boundary pixels are
    wrapped around to the opposite edge pixels in 'a'.

    >>> a = num.arange(16, shape=(4,4))
    >>> frame_wrap(a, (8,8))
    array([[10, 11,  8,  9, 10, 11,  8,  9],
           [14, 15, 12, 13, 14, 15, 12, 13],
           [ 2,  3,  0,  1,  2,  3,  0,  1],
           [ 6,  7,  4,  5,  6,  7,  4,  5],
           [10, 11,  8,  9, 10, 11,  8,  9],
           [14, 15, 12, 13, 14, 15, 12, 13],
           [ 2,  3,  0,  1,  2,  3,  0,  1],
           [ 6,  7,  4,  5,  6,  7,  4,  5]])

    """
    
    b = num.zeros(shape, typecode=a.type())
    delta = (num.array(b.shape) - num.array(a.shape))
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = a.shape[0] + dy
    mx = a.shape[1] + dx
    sy = delta[0] - dy
    sx = delta[1] - dx
    
    b[dy:my, dx:mx] = a                  # center
    b[:dy,dx:mx]  = a[-dy:,:]            # top
    b[my:,dx:mx]  = a[:sy,:]             # bottom
    b[dy:my,:dx]  = a[:,-dx:]            # left
    b[dy:my,mx:]  = a[:, :sx]            # right
    b[:dy,:dx]    = a[-dy:,-dx:]         # topleft
    b[:dy,mx:]    = a[-dy:,:sx ]         # topright
    b[my:,:dx]    = a[:sy, -dx:]         # bottomleft
    b[my:,mx:]    = a[:sy, :sx]          # bottomright
    return b
Пример #18
0
def frame_nearest(a, shape, cval=None):
    """frame_nearest creates an oversized copy of 'a' with new 'shape'
    and the contents of 'a' in the center.  The boundary pixels are
    copied from the nearest edge pixel in 'a'.

    >>> a = num.arange(16, shape=(4,4))
    >>> frame_nearest(a, (8,8))
    array([[ 0,  0,  0,  1,  2,  3,  3,  3],
           [ 0,  0,  0,  1,  2,  3,  3,  3],
           [ 0,  0,  0,  1,  2,  3,  3,  3],
           [ 4,  4,  4,  5,  6,  7,  7,  7],
           [ 8,  8,  8,  9, 10, 11, 11, 11],
           [12, 12, 12, 13, 14, 15, 15, 15],
           [12, 12, 12, 13, 14, 15, 15, 15],
           [12, 12, 12, 13, 14, 15, 15, 15]])
           
    """

    b = num.zeros(shape, typecode=a.type())
    delta = (num.array(b.shape) - num.array(a.shape))
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = a.shape[0] + dy
    mx = a.shape[1] + dx

    b[dy:my, dx:mx] = a  # center
    b[:dy, dx:mx] = a[0:1, :]  # top
    b[my:, dx:mx] = a[-1:, :]  # bottom
    b[dy:my, :dx] = a[:, 0:1]  # left
    b[dy:my, mx:] = a[:, -1:]  # right
    b[:dy, :dx] = a[0, 0]  # topleft
    b[:dy, mx:] = a[0, -1]  # topright
    b[my:, :dx] = a[-1, 0]  # bottomleft
    b[my:, mx:] = a[-1, -1]  # bottomright

    return b
Пример #19
0
def frame_reflect(a, shape, cval=None):
    """frame_reflect creates an oversized copy of 'a' with new 'shape'
    and the contents of 'a' in the center.  The boundary pixels are
    reflected from the nearest edge pixels in 'a'.

    >>> a = num.arange(16, shape=(4,4))
    >>> frame_reflect(a, (8,8))
    array([[ 5,  4,  4,  5,  6,  7,  7,  6],
           [ 1,  0,  0,  1,  2,  3,  3,  2],
           [ 1,  0,  0,  1,  2,  3,  3,  2],
           [ 5,  4,  4,  5,  6,  7,  7,  6],
           [ 9,  8,  8,  9, 10, 11, 11, 10],
           [13, 12, 12, 13, 14, 15, 15, 14],
           [13, 12, 12, 13, 14, 15, 15, 14],
           [ 9,  8,  8,  9, 10, 11, 11, 10]])
    """

    b = num.zeros(shape, typecode=a.type())
    delta = (num.array(b.shape) - num.array(a.shape))
    dy = delta[0] // 2
    dx = delta[1] // 2
    my = a.shape[0] + dy
    mx = a.shape[1] + dx
    sy = delta[0] - dy
    sx = delta[1] - dx

    b[dy:my, dx:mx] = a  # center
    b[:dy, dx:mx] = a[:dy, :][::-1, :]  # top
    b[my:, dx:mx] = a[-sy:, :][::-1, :]  # bottom
    b[dy:my, :dx] = a[:, :dx][:, ::-1]  # left
    b[dy:my, mx:] = a[:, -sx:][:, ::-1]  # right
    b[:dy, :dx] = a[:dy, :dx][::-1, ::-1]  # topleft
    b[:dy, mx:] = a[:dy, -sx:][::-1, ::-1]  # topright
    b[my:, :dx] = a[-sy:, :dx][::-1, ::-1]  # bottomleft
    b[my:, mx:] = a[-sy:, -sx:][::-1, ::-1]  # bottomright
    return b
Пример #20
0
def _translate(a, dx, dy, output=None, mode="nearest", cval=0.0):
    """_translate does positive sub-pixel shifts using bilinear interpolation."""
    
    assert 0 <= dx < 1.0
    assert 0 <= dy < 1.0
    
    w = (1-dy) * (1-dx)
    x = (1-dy) * dx
    y = (1-dx) * dy
    z = dx * dy
    
    kernel = num.array([
        [ z, y ],
        [ x, w ],
        ])
    
    return numarray.convolve.correlate2d(a, kernel, output, mode, cval)
Пример #21
0
def linear_least_squares(a, b, rcond=1.e-10):
    """solveLinearLeastSquares(a,b) returns x,resids,rank,s 
where x minimizes 2-norm(|b - Ax|) 
      resids is the sum square residuals
      rank is the rank of A
      s is an rank of the singual values of A in desending order

If b is a matrix then x is also a matrix with corresponding columns.
If the rank of A is less than the number of columns of A or greater than
the numer of rows, then residuals will be returned as an empty array
otherwise resids = sum((b-dot(A,x)**2).
Singular values less than s[0]*rcond are treated as zero.
"""
    one_eq = len(b.getshape()) == 1
    if one_eq:
        b = b[:, num.NewAxis]
    _assertRank2(a, b)
    m  = a.getshape()[0]
    n  = a.getshape()[1]
    n_rhs = b.getshape()[1]
    ldb = max(n,m)
    if m != b.getshape()[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t =_commonType(a, b)
    real_t = _array_type[0][_array_precision[t]]
    bstar = num.zeros((ldb,n_rhs),t)
    bstar[:b.getshape()[0],:n_rhs] = copy.copy(b)
    a,bstar = _castCopyAndTranspose(t, a, bstar)
    s = num.zeros((min(m,n),),real_t)
    nlvl = max( 0, int( math.log( float(min( m,n ))/2. ) ) + 1 )
    iwork = num.zeros((3*min(m,n)*nlvl+11*min(m,n),), 'l')
    if _array_kind[t] == 1: # Complex routines take different arguments
        lapack_routine = lapack_lite2.zgelsd
        lwork = 1
        rwork = num.zeros((lwork,), real_t)
        work = num.zeros((lwork,),t)
        results = lapack_routine( m, n, n_rhs, a, m, bstar,ldb , s, rcond,
                        0,work,-1,rwork,iwork,0 )
        lwork = int(abs(work[0]))
        rwork = num.zeros((lwork,),real_t)
        a_real = num.zeros((m,n),real_t)
        bstar_real = num.zeros((ldb,n_rhs,),real_t)
        results = lapack_lite2.dgelsd( m, n, n_rhs, a_real, m, bstar_real,ldb , s, rcond,
                        0,rwork,-1,iwork,0 )
        lrwork = int(rwork[0])
        work = num.zeros((lwork,), t)
        rwork = num.zeros((lrwork,), real_t)
        results = lapack_routine( m, n, n_rhs, a, m, bstar,ldb , s, rcond,
                        0,work,lwork,rwork,iwork,0 )
    else:
        lapack_routine = lapack_lite2.dgelsd
        lwork = 1
        work = num.zeros((lwork,), t)
        results = lapack_routine( m, n, n_rhs, a, m, bstar,ldb , s, rcond,
                        0,work,-1,iwork,0 )
        lwork = int(work[0])
        work = num.zeros((lwork,), t)
        results = lapack_routine( m, n, n_rhs, a, m, bstar,ldb , s, rcond,
                        0,work,lwork,iwork,0 )
    if results['info'] > 0:
        raise LinAlgError, 'SVD did not converge in Linear Least Squares'
    resids = num.array([],type=t)
    if one_eq:
        x = copy.copy(num.ravel(bstar)[:n])
        if (results['rank']==n) and (m>n):
            resids = num.array([num.sum((num.ravel(bstar)[n:])**2)])
    else:
        x = copy.copy(num.transpose(bstar)[:n,:])
        if (results['rank']==n) and (m>n):
            resids = copy.copy(num.sum((num.transpose(bstar)[n:,:])**2))
    return x,resids,results['rank'],copy.copy(s[:min(n,m)])