예제 #1
0
def pinv(a, rcond=1e-15 ):
    """
    Compute the (Moore-Penrose) pseudo-inverse of a matrix.

    Calculate the generalized inverse of a matrix using its
    singular-value decomposition (SVD) and including all
    `large` singular values.

    Parameters
    ----------
    a : array_like (M, N)
      Matrix to be pseudo-inverted.
    rcond : float
      Cutoff for `small` singular values.
      Singular values smaller than rcond*largest_singular_value are
      considered zero.

    Returns
    -------
    B : ndarray (N, M)
      The pseudo-inverse of `a`. If `a` is an np.matrix instance, then so
      is `B`.


    Raises
    ------
    LinAlgError
      In case SVD computation does not converge.

    Examples
    --------
    >>> a = np.random.randn(9, 6)
    >>> B = np.linalg.pinv(a)
    >>> np.allclose(a, np.dot(a, np.dot(B, a)))
    True
    >>> np.allclose(B, np.dot(B, np.dot(a, B)))
    True

    """
    a, wrap = _makearray(a)
    _assertNonEmpty(a)
    a = a.conjugate()
    u, s, vt = svd(a, 0)
    m = u.shape[0]
    n = vt.shape[1]
    cutoff = rcond*maximum.reduce(s)
    for i in range(min(n, m)):
        if s[i] > cutoff:
            s[i] = 1./s[i]
        else:
            s[i] = 0.;
    res = dot(transpose(vt), multiply(s[:, newaxis],transpose(u)))
    return wrap(res)
예제 #2
0
def pinv(a, rcond=1e-15):
    """
    Compute the (Moore-Penrose) pseudo-inverse of a matrix.

    Calculate the generalized inverse of a matrix using its
    singular-value decomposition (SVD) and including all
    `large` singular values.

    Parameters
    ----------
    a : array_like (M, N)
      Matrix to be pseudo-inverted.
    rcond : float
      Cutoff for `small` singular values.
      Singular values smaller than rcond*largest_singular_value are
      considered zero.

    Returns
    -------
    B : ndarray (N, M)
      The pseudo-inverse of `a`. If `a` is an np.matrix instance, then so
      is `B`.


    Raises
    ------
    LinAlgError
      In case SVD computation does not converge.

    Examples
    --------
    >>> a = np.random.randn(9, 6)
    >>> B = np.linalg.pinv(a)
    >>> np.allclose(a, np.dot(a, np.dot(B, a)))
    True
    >>> np.allclose(B, np.dot(B, np.dot(a, B)))
    True

    """
    a, wrap = _makearray(a)
    _assertNonEmpty(a)
    a = a.conjugate()
    u, s, vt = svd(a, 0)
    m = u.shape[0]
    n = vt.shape[1]
    cutoff = rcond * maximum.reduce(s)
    for i in range(min(n, m)):
        if s[i] > cutoff:
            s[i] = 1. / s[i]
        else:
            s[i] = 0.
    res = dot(transpose(vt), multiply(s[:, newaxis], transpose(u)))
    return wrap(res)
예제 #3
0
def pinv(a, rcond=1e-15 ):
    """Compute the (Moore-Penrose) pseudo-inverse of a matrix.

    Calculate a generalized inverse of a matrix using its
    singular-value decomposition and including all 'large' singular
    values.

    Parameters
    ----------
    a : array-like, shape (M, N)
        Matrix to be pseudo-inverted
    rcond : float
        Cutoff for 'small' singular values.
        Singular values smaller than rcond*largest_singular_value are
        considered zero.

    Returns
    -------
    B : array, shape (N, M)
        If a is a matrix, then so is B.

    Raises LinAlgError if SVD computation does not converge

    Examples
    --------
    >>> from numpy import *
    >>> a = random.randn(9, 6)
    >>> B = linalg.pinv(a)
    >>> allclose(a, dot(a, dot(B, a)))
    True
    >>> allclose(B, dot(B, dot(a, B)))
    True

    """
    a, wrap = _makearray(a)
    _assertNonEmpty(a)
    a = a.conjugate()
    u, s, vt = svd(a, 0)
    m = u.shape[0]
    n = vt.shape[1]
    cutoff = rcond*maximum.reduce(s)
    for i in range(min(n, m)):
        if s[i] > cutoff:
            s[i] = 1./s[i]
        else:
            s[i] = 0.;
    res = dot(transpose(vt), multiply(s[:, newaxis],transpose(u)))
    return wrap(res)
예제 #4
0
파일: linalg.py 프로젝트: lisarosalina/App
def pinv(a, rcond=1e-15):
    """Compute the (Moore-Penrose) pseudo-inverse of a matrix.

    Calculate a generalized inverse of a matrix using its
    singular-value decomposition and including all 'large' singular
    values.

    Parameters
    ----------
    a : array-like, shape (M, N)
        Matrix to be pseudo-inverted
    rcond : float
        Cutoff for 'small' singular values.
        Singular values smaller than rcond*largest_singular_value are
        considered zero.

    Returns
    -------
    B : array, shape (N, M)
        If a is a matrix, then so is B.

    Raises LinAlgError if SVD computation does not converge

    Examples
    --------
    >>> from numpy import *
    >>> a = random.randn(9, 6)
    >>> B = linalg.pinv(a)
    >>> allclose(a, dot(a, dot(B, a)))
    True
    >>> allclose(B, dot(B, dot(a, B)))
    True

    """
    a, wrap = _makearray(a)
    _assertNonEmpty(a)
    a = a.conjugate()
    u, s, vt = svd(a, 0)
    m = u.shape[0]
    n = vt.shape[1]
    cutoff = rcond * maximum.reduce(s)
    for i in range(min(n, m)):
        if s[i] > cutoff:
            s[i] = 1. / s[i]
        else:
            s[i] = 0.
    res = dot(transpose(vt), multiply(s[:, newaxis], transpose(u)))
    return wrap(res)
예제 #5
0
def pinv(a, rcond=1e-15 ):
    """Return the (Moore-Penrose) pseudo-inverse of a 2-d array

    This method computes the generalized inverse using the
    singular-value decomposition and all singular values larger than
    rcond of the largest.
    """
    a, wrap = _makearray(a)
    a = a.conjugate()
    u, s, vt = svd(a, 0)
    m = u.shape[0]
    n = vt.shape[1]
    cutoff = rcond*maximum.reduce(s)
    for i in range(min(n, m)):
        if s[i] > cutoff:
            s[i] = 1./s[i]
        else:
            s[i] = 0.;
    return wrap(dot(transpose(vt),
                       multiply(s[:, newaxis],transpose(u))))
예제 #6
0
def pinv(a, rcond=1e-15):
    """Return the (Moore-Penrose) pseudo-inverse of a 2-d array

    This method computes the generalized inverse using the
    singular-value decomposition and all singular values larger than
    rcond of the largest.
    """
    a, wrap = _makearray(a)
    _assertNonEmpty(a)
    a = a.conjugate()
    u, s, vt = svd(a, 0)
    m = u.shape[0]
    n = vt.shape[1]
    cutoff = rcond * maximum.reduce(s)
    for i in range(min(n, m)):
        if s[i] > cutoff:
            s[i] = 1. / s[i]
        else:
            s[i] = 0.
    return wrap(dot(transpose(vt), multiply(s[:, newaxis], transpose(u))))
예제 #7
0
파일: Math.py 프로젝트: thunder001/MetaXcan
def _inv(a, cf, rcond, epsilon):
    """
    modified pseudo inverse
    """

    def _assertNoEmpty2d(*arrays):
        for a in arrays:
            if a.size == 0 and product(a.shape[-2:]) == 0:
                raise RuntimeError("Arrays cannot be empty")

    def _makearray(a):
        new = asarray(a)
        wrap = getattr(a, "__array_prepare__", new.__array_wrap__)
        return new, wrap

    a, wrap = _makearray(a)
    _assertNoEmpty2d(a)

    if epsilon is not None:
        epsilon = numpy.repeat(epsilon, a.shape[0])
        epsilon = numpy.diag(epsilon)
        a = a + epsilon
    a = a.conjugate()
    #WARNING! the "s" eigenvalues might not equal the eigenvalues of eigh
    u, s, vt = numpy.linalg.svd(a, 0)
    m = u.shape[0]
    n = vt.shape[1]
    eigen = numpy.copy(s)

    # cutoff = rcond*maximum.reduce(s)
    cutoff = cf(s, rcond)
    for i in range(min(n, m)):
        # The first Singular Value will always be selected because we want at least one, and the first is the highest
        if s[i] >= cutoff or i==0:
            s[i] = 1. / s[i]
        else:
            s[i] = 0.

    n_indep = numpy.count_nonzero(s)
    res = dot(transpose(vt), multiply(s[:, newaxis], transpose(u)))
    return wrap(res), n_indep, eigen
예제 #8
0
 def _rawcb(self, msg):
     #beam tilt is output by ps0 command, 600khz 30degs
     ba_s = map(np.sin, self.beam_angles)
     ba_c = map(np.cos, self.beam_angles)
     A = np.zeros((len(msg.beam_velocity), 3))
     A[0] = [-ba_s[0], 0, -ba_c[0]]
     A[1] = [ba_s[1],  0, -ba_c[1]]
     A[2] = [0, +ba_s[2], -ba_c[2]]
     A[3] = [0, -ba_s[3], -ba_c[3]]
     b = [x for x in msg.beam_velocity if x is not math.isnan(x)]
     A = np.dot(inv(np.dot(transpose(A), A)), transpose(A))
     x = np.dot(A, b)
     if(abs(x[0]) > 5 or abs(x[1]) > 5 or abs(x[2]) > 5):
         return
     x = [x[1] * np.sin(self.ea) + x[0] * np.sin(self.ea),
         -x[1] * np.cos(self.ea) + x[0] * np.cos(self.ea), x[2]]
     self.vel_out.publish(dvl_vel(
                 header=msg.header,
                 velocity=Vector3(*x)
             ))
     self.altitude_out.publish(Float32(msg.altitude))
예제 #9
0
            object.__setattr__(self, attr, value)

    # Only called after other approaches fail.
    def __getattr__(self, attr):
        if (attr == 'array'):
            return object.__getattribute__(self, attr)
        return self.array.__getattribute__(attr)


#############################################################
# Test of class container
#############################################################
if __name__ == '__main__':
    temp = reshape(arange(10000), (100, 100))

    ua = container(temp)
    # new object created begin test
    print(dir(ua))
    print(shape(ua), ua.shape)  # I have changed Numeric.py

    ua_small = ua[:3, :5]
    print(ua_small)
    # this did not change ua[0,0], which is not normal behavior
    ua_small[0, 0] = 10
    print(ua_small[0, 0], ua[0, 0])
    print(sin(ua_small) / 3. * 6. + sqrt(ua_small**2))
    print(less(ua_small, 103), type(less(ua_small, 103)))
    print(type(ua_small * reshape(arange(15), shape(ua_small))))
    print(reshape(ua_small, (5, 3)))
    print(transpose(ua_small))
예제 #10
0
def Heigenvectors(A):
    w, v = linalg.eigh(A)
    return w, transpose(v)
예제 #11
0
def lstsq(a, b, rcond=-1):
    """
    Return the least-squares solution to an equation.

    Solves the equation `a x = b` by computing a vector `x` that minimizes
    the norm `|| b - a x ||`.

    Parameters
    ----------
    a : array_like, shape (M, N)
        Input equation coefficients.
    b : array_like, shape (M,) or (M, K)
        Equation target values.  If `b` is two-dimensional, the least
        squares solution is calculated for each of the `K` target sets.
    rcond : float, optional
        Cutoff for ``small`` singular values of `a`.
        Singular values smaller than `rcond` times the largest singular
        value are  considered zero.

    Returns
    -------
    x : ndarray, shape(N,) or (N, K)
         Least squares solution.  The shape of `x` depends on the shape of
         `b`.
    residues : ndarray, shape(), (1,), or (K,)
        Sums of residues; squared Euclidian norm for each column in
        `b - a x`.
        If the rank of `a` is < N or > M, this is an empty array.
        If `b` is 1-dimensional, this is a (1,) shape array.
        Otherwise the shape is (K,).
    rank : integer
        Rank of matrix `a`.
    s : ndarray, shape(min(M,N),)
        Singular values of `a`.

    Raises
    ------
    LinAlgError
        If computation does not converge.

    Notes
    -----
    If `b` is a matrix, then all array results returned as
    matrices.

    Examples
    --------
    Fit a line, ``y = mx + c``, through some noisy data-points:

    >>> x = np.array([0, 1, 2, 3])
    >>> y = np.array([-1, 0.2, 0.9, 2.1])

    By examining the coefficients, we see that the line should have a
    gradient of roughly 1 and cuts the y-axis at more-or-less -1.

    We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
    and ``p = [[m], [c]]``.  Now use `lstsq` to solve for `p`:

    >>> A = np.vstack([x, np.ones(len(x))]).T
    >>> A
    array([[ 0.,  1.],
           [ 1.,  1.],
           [ 2.,  1.],
           [ 3.,  1.]])

    >>> m, c = np.linalg.lstsq(A, y)[0]
    >>> print m, c
    1.0 -0.95

    Plot the data along with the fitted line:

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(x, y, 'o', label='Original data', markersize=10)
    >>> plt.plot(x, m*x + c, 'r', label='Fitted line')
    >>> plt.legend()
    >>> plt.show()

    """
    import math
    a, _ = _makearray(a)
    b, wrap = _makearray(b)
    is_1d = len(b.shape) == 1
    if is_1d:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m = a.shape[0]
    n = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0], :n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n), ), real_t)
    nlvl = max(0, int(math.log(float(min(m, n)) / 2.)) + 1)
    iwork = zeros((3 * min(m, n) * nlvl + 11 * min(m, n), ), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork, ), real_t)
        work = 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 = zeros((lwork, ), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((
            ldb,
            n_rhs,
        ), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m, bstar_real, ldb,
                                     s, rcond, 0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork, ), t)
        rwork = 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_lite.dgelsd
        lwork = 1
        work = 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 = 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 = array([], t)
    if is_1d:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n, :], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:, :])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), wrap(resids), results['rank'], st
예제 #12
0
            self.array.__setattr__(attr, value)
        except AttributeError:
            object.__setattr__(self, attr, value)

    # Only called after other approaches fail.
    def __getattr__(self,attr):
        if (attr == 'array'):
            return object.__getattribute__(self, attr)
        return self.array.__getattribute__(attr)

#############################################################
# Test of class container
#############################################################
if __name__ == '__main__':
    temp=reshape(arange(10000),(100,100))

    ua=container(temp)
    # new object created begin test
    print dir(ua)
    print shape(ua),ua.shape # I have changed Numeric.py

    ua_small=ua[:3,:5]
    print ua_small
    ua_small[0,0]=10  # this did not change ua[0,0], which is not normal behavior
    print ua_small[0,0],ua[0,0]
    print sin(ua_small)/3.*6.+sqrt(ua_small**2)
    print less(ua_small,103),type(less(ua_small,103))
    print type(ua_small*reshape(arange(15),shape(ua_small)))
    print reshape(ua_small,(5,3))
    print transpose(ua_small)
예제 #13
0
def lstsq(a, b, rcond=-1):
    """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 the rank of the singular values of A in descending 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 number 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.
"""
    import math
    a = asarray(a)
    b, wrap = _makearray(b)
    one_eq = len(b.shape) == 1
    if one_eq:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m  = a.shape[0]
    n  = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0],:n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n),), real_t)
    nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 )
    iwork = zeros((3*min(m, n)*nlvl+11*min(m, n),), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork,), real_t)
        work = 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 = zeros((lwork,), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((ldb, n_rhs,), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m,
                                     bstar_real, ldb, s, rcond,
                                     0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork,), t)
        rwork = 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_lite.dgelsd
        lwork = 1
        work = 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 = 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 = array([], t)
    if one_eq:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:,:])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), resids, results['rank'], st
예제 #14
0
def Heigenvectors(A):
    w, v = linalg.eigh(A)
    return w, transpose(v)
예제 #15
0
def coarseMolSurface(molFrag,XYZd,isovalue=5.0,resolution=-0.4,padding=0.0, name='CoarseMolSurface',geom=None):
	"""
	Function adapted from the Vision network which compute a coarse molecular
	surface in PMV

	@type  molFrag: MolKit.AtomSet
	@param molFrag: the atoms selection
	@type  XYZd: array
	@param XYZd: shape of the volume
	@type  isovalue: float
	@param isovalue: isovalue for the isosurface computation
	@type  resolution: float
	@param resolution: resolution of the final mesh
	@type  padding: float
	@param padding: the padding
	@type  name: string
	@param name: the name of the resultante geometry
	@type  geom: DejaVu.Geom
	@param geom: update geom instead of creating a new one

	@rtype:   DejaVu.Geom
	@return:  the created or updated DejaVu.Geom
	"""
	import pdb
	from MolKit.molecule import Atom
	atoms = molFrag.findType(Atom)
	coords = atoms.coords
	radii = atoms.vdwRadius
	from UTpackages.UTblur import blur
	import numpy.core as Numeric

	volarr, origin, span = blur.generateBlurmap(coords, radii, XYZd,resolution, padding = 0.0)
	volarr.shape = (XYZd[0],XYZd[1],XYZd[2])
	volarr = Numeric.ascontiguousarray(Numeric.transpose(volarr), 'f')

	weights =  Numeric.ones(len(radii), 'f')
	h = {}
	from Volume.Grid3D import Grid3DF
	maskGrid = Grid3DF( volarr, origin, span , h)
	h['amin'], h['amax'],h['amean'],h['arms']= maskGrid.stats()

	from UTpackages.UTisocontour import isocontour
	isocontour.setVerboseLevel(0)

	data = maskGrid.data

	origin = Numeric.array(maskGrid.origin).astype('f')
	stepsize = Numeric.array(maskGrid.stepSize).astype('f')

	if data.dtype.char!=Numeric.float32:
		data = data.astype('f')#Numeric.Float32)

	newgrid3D = Numeric.ascontiguousarray(Numeric.reshape( Numeric.transpose(data),
										  (1, 1)+tuple(data.shape) ), data.dtype.char)

	ndata = isocontour.newDatasetRegFloat3D(newgrid3D, origin, stepsize)

	isoc = isocontour.getContour3d(ndata, 0, 0, isovalue,
									   isocontour.NO_COLOR_VARIABLE)
	vert = Numeric.zeros((isoc.nvert,3)).astype('f')
	norm = Numeric.zeros((isoc.nvert,3)).astype('f')
	col = Numeric.zeros((isoc.nvert)).astype('f')
	tri = Numeric.zeros((isoc.ntri,3)).astype('i')

	isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)

	if maskGrid.crystal:
		vert = maskGrid.crystal.toCartesian(vert)

	return (vert, tri)
예제 #16
0
파일: linalg.py 프로젝트: lisarosalina/App
def lstsq(a, b, rcond=-1):
    """Compute least-squares solution to equation :math:`a x = b`

    Compute a vector x such that the 2-norm :math:`|b - a x|` is minimised.

    Parameters
    ----------
    a : array-like, shape (M, N)
    b : array-like, shape (M,) or (M, K)
    rcond : float
        Cutoff for 'small' singular values.
        Singular values smaller than rcond*largest_singular_value are
        considered zero.

    Raises LinAlgError if computation does not converge

    Returns
    -------
    x : array, shape (N,) or (N, K) depending on shape of b
        Least-squares solution
    residues : array, shape () or (1,) or (K,)
        Sums of residues, squared 2-norm for each column in :math:`b - a x`
        If rank of matrix a is < N or > M this is an empty array.
        If b was 1-d, this is an (1,) shape array, otherwise the shape is (K,)
    rank : integer
        Rank of matrix a
    s : array, shape (min(M,N),)
        Singular values of a

    If b is a matrix, then all results except the rank are also returned as
    matrices.

    """
    import math
    a, _ = _makearray(a)
    b, wrap = _makearray(b)
    is_1d = len(b.shape) == 1
    if is_1d:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m = a.shape[0]
    n = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0], :n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n), ), real_t)
    nlvl = max(0, int(math.log(float(min(m, n)) / 2.)) + 1)
    iwork = zeros((3 * min(m, n) * nlvl + 11 * min(m, n), ), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork, ), real_t)
        work = 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 = zeros((lwork, ), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((
            ldb,
            n_rhs,
        ), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m, bstar_real, ldb,
                                     s, rcond, 0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork, ), t)
        rwork = 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_lite.dgelsd
        lwork = 1
        work = 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 = 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 = array([], t)
    if is_1d:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n, :], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:, :])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), wrap(resids), results['rank'], st
예제 #17
0
파일: linalg.py 프로젝트: lisarosalina/App
def _castCopyAndTranspose(type, *arrays):
    if len(arrays) == 1:
        return transpose(arrays[0]).astype(type)
    else:
        return [transpose(a).astype(type) for a in arrays]
예제 #18
0
def lstsq(a, b, rcond=-1):
    """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 the rank of the singular values of A in descending 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 number 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.
"""
    import math
    a = asarray(a)
    b, wrap = _makearray(b)
    one_eq = len(b.shape) == 1
    if one_eq:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m = a.shape[0]
    n = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0], :n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n), ), real_t)
    nlvl = max(0, int(math.log(float(min(m, n)) / 2.)) + 1)
    iwork = zeros((3 * min(m, n) * nlvl + 11 * min(m, n), ), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork, ), real_t)
        work = 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 = zeros((lwork, ), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((
            ldb,
            n_rhs,
        ), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m, bstar_real, ldb,
                                     s, rcond, 0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork, ), t)
        rwork = 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_lite.dgelsd
        lwork = 1
        work = 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 = 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 = array([], t)
    if one_eq:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n, :], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:, :])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), resids, results['rank'], st
예제 #19
0
        except AttributeError:
            object.__setattr__(self, attr, value)

    # Only called after other approaches fail.
    def __getattr__(self, attr):
        if (attr == 'array'):
            return object.__getattribute__(self, attr)
        return self.array.__getattribute__(attr)

#############################################################
# Test of class container
#############################################################
if __name__ == '__main__':
    temp = reshape(arange(10000), (100, 100))

    ua = container(temp)
    # new object created begin test
    print(dir(ua))
    print(shape(ua), ua.shape)  # I have changed Numeric.py

    ua_small = ua[:3, :5]
    print(ua_small)
    # this did not change ua[0,0], which is not normal behavior
    ua_small[0, 0] = 10
    print(ua_small[0, 0], ua[0, 0])
    print(sin(ua_small) / 3. * 6. + sqrt(ua_small ** 2))
    print(less(ua_small, 103), type(less(ua_small, 103)))
    print(type(ua_small * reshape(arange(15), shape(ua_small))))
    print(reshape(ua_small, (5, 3)))
    print(transpose(ua_small))
예제 #20
0
def lstsq(a, b, rcond=-1):
    """Compute least-squares solution to equation :math:`a x = b`

    Compute a vector x such that the 2-norm :math:`|b - a x|` is minimised.

    Parameters
    ----------
    a : array-like, shape (M, N)
    b : array-like, shape (M,) or (M, K)
    rcond : float
        Cutoff for 'small' singular values.
        Singular values smaller than rcond*largest_singular_value are
        considered zero.

    Raises LinAlgError if computation does not converge

    Returns
    -------
    x : array, shape (N,) or (N, K) depending on shape of b
        Least-squares solution
    residues : array, shape () or (1,) or (K,)
        Sums of residues, squared 2-norm for each column in :math:`b - a x`
        If rank of matrix a is < N or > M this is an empty array.
        If b was 1-d, this is an (1,) shape array, otherwise the shape is (K,)
    rank : integer
        Rank of matrix a
    s : array, shape (min(M,N),)
        Singular values of a

    If b is a matrix, then all results except the rank are also returned as
    matrices.

    """
    import math
    a, _ = _makearray(a)
    b, wrap = _makearray(b)
    is_1d = len(b.shape) == 1
    if is_1d:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m  = a.shape[0]
    n  = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0],:n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n),), real_t)
    nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 )
    iwork = zeros((3*min(m, n)*nlvl+11*min(m, n),), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork,), real_t)
        work = 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 = zeros((lwork,), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((ldb, n_rhs,), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m,
                                     bstar_real, ldb, s, rcond,
                                     0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork,), t)
        rwork = 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_lite.dgelsd
        lwork = 1
        work = 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 = 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 = array([], t)
    if is_1d:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:,:])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), wrap(resids), results['rank'], st
예제 #21
0
def lstsq(a, b, rcond=-1):
    """
    Return the least-squares solution to an equation.

    Solves the equation `a x = b` by computing a vector `x` that minimizes
    the norm `|| b - a x ||`.

    Parameters
    ----------
    a : array_like, shape (M, N)
        Input equation coefficients.
    b : array_like, shape (M,) or (M, K)
        Equation target values.  If `b` is two-dimensional, the least
        squares solution is calculated for each of the `K` target sets.
    rcond : float, optional
        Cutoff for ``small`` singular values of `a`.
        Singular values smaller than `rcond` times the largest singular
        value are  considered zero.

    Returns
    -------
    x : ndarray, shape(N,) or (N, K)
         Least squares solution.  The shape of `x` depends on the shape of
         `b`.
    residues : ndarray, shape(), (1,), or (K,)
        Sums of residues; squared Euclidian norm for each column in
        `b - a x`.
        If the rank of `a` is < N or > M, this is an empty array.
        If `b` is 1-dimensional, this is a (1,) shape array.
        Otherwise the shape is (K,).
    rank : integer
        Rank of matrix `a`.
    s : ndarray, shape(min(M,N),)
        Singular values of `a`.

    Raises
    ------
    LinAlgError
        If computation does not converge.

    Notes
    -----
    If `b` is a matrix, then all array results returned as
    matrices.

    Examples
    --------
    Fit a line, ``y = mx + c``, through some noisy data-points:

    >>> x = np.array([0, 1, 2, 3])
    >>> y = np.array([-1, 0.2, 0.9, 2.1])

    By examining the coefficients, we see that the line should have a
    gradient of roughly 1 and cuts the y-axis at more-or-less -1.

    We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
    and ``p = [[m], [c]]``.  Now use `lstsq` to solve for `p`:

    >>> A = np.vstack([x, np.ones(len(x))]).T
    >>> A
    array([[ 0.,  1.],
           [ 1.,  1.],
           [ 2.,  1.],
           [ 3.,  1.]])

    >>> m, c = np.linalg.lstsq(A, y)[0]
    >>> print m, c
    1.0 -0.95

    Plot the data along with the fitted line:

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(x, y, 'o', label='Original data', markersize=10)
    >>> plt.plot(x, m*x + c, 'r', label='Fitted line')
    >>> plt.legend()
    >>> plt.show()

    """
    import math
    a, _ = _makearray(a)
    b, wrap = _makearray(b)
    is_1d = len(b.shape) == 1
    if is_1d:
        b = b[:, newaxis]
    _assertRank2(a, b)
    m  = a.shape[0]
    n  = a.shape[1]
    n_rhs = b.shape[1]
    ldb = max(n, m)
    if m != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t, result_t = _commonType(a, b)
    real_t = _linalgRealType(t)
    bstar = zeros((ldb, n_rhs), t)
    bstar[:b.shape[0],:n_rhs] = b.copy()
    a, bstar = _fastCopyAndTranspose(t, a, bstar)
    s = zeros((min(m, n),), real_t)
    nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 )
    iwork = zeros((3*min(m, n)*nlvl+11*min(m, n),), fortran_int)
    if isComplexType(t):
        lapack_routine = lapack_lite.zgelsd
        lwork = 1
        rwork = zeros((lwork,), real_t)
        work = 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 = zeros((lwork,), real_t)
        a_real = zeros((m, n), real_t)
        bstar_real = zeros((ldb, n_rhs,), real_t)
        results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m,
                                     bstar_real, ldb, s, rcond,
                                     0, rwork, -1, iwork, 0)
        lrwork = int(rwork[0])
        work = zeros((lwork,), t)
        rwork = 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_lite.dgelsd
        lwork = 1
        work = 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 = 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 = array([], t)
    if is_1d:
        x = array(ravel(bstar)[:n], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t)
    else:
        x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True)
        if results['rank'] == n and m > n:
            resids = sum((transpose(bstar)[n:,:])**2, axis=0).astype(result_t)
    st = s[:min(n, m)].copy().astype(_realType(result_t))
    return wrap(x), wrap(resids), results['rank'], st
예제 #22
0
def _castCopyAndTranspose(type, *arrays):
    if len(arrays) == 1:
        return transpose(arrays[0]).astype(type)
    else:
        return [transpose(a).astype(type) for a in arrays]
예제 #23
0
            object.__setattr__(self, attr, value)

    # Only called after other approaches fail.
    def __getattr__(self, attr):
        if (attr == 'array'):
            return object.__getattribute__(self, attr)
        return self.array.__getattribute__(attr)


#############################################################
# Test of class container
#############################################################
if __name__ == '__main__':
    temp = reshape(arange(10000), (100, 100))

    ua = container(temp)
    # new object created begin test
    print dir(ua)
    print shape(ua), ua.shape  # I have changed Numeric.py

    ua_small = ua[:3, :5]
    print ua_small
    ua_small[
        0, 0] = 10  # this did not change ua[0,0], which is not normal behavior
    print ua_small[0, 0], ua[0, 0]
    print sin(ua_small) / 3. * 6. + sqrt(ua_small**2)
    print less(ua_small, 103), type(less(ua_small, 103))
    print type(ua_small * reshape(arange(15), shape(ua_small)))
    print reshape(ua_small, (5, 3))
    print transpose(ua_small)
예제 #24
0
def coarseMolSurface(molFrag,
                     XYZd,
                     isovalue=5.0,
                     resolution=-0.4,
                     padding=0.0,
                     name='CoarseMolSurface',
                     geom=None):
    """
	Function adapted from the Vision network which compute a coarse molecular
	surface in PMV

	@type  molFrag: MolKit.AtomSet
	@param molFrag: the atoms selection
	@type  XYZd: array
	@param XYZd: shape of the volume
	@type  isovalue: float
	@param isovalue: isovalue for the isosurface computation
	@type  resolution: float
	@param resolution: resolution of the final mesh
	@type  padding: float
	@param padding: the padding
	@type  name: string
	@param name: the name of the resultante geometry
	@type  geom: DejaVu.Geom
	@param geom: update geom instead of creating a new one

	@rtype:   DejaVu.Geom
	@return:  the created or updated DejaVu.Geom
	"""
    import pdb
    from MolKit.molecule import Atom
    atoms = molFrag.findType(Atom)
    coords = atoms.coords
    radii = atoms.vdwRadius
    from UTpackages.UTblur import blur
    import numpy.core as Numeric

    volarr, origin, span = blur.generateBlurmap(coords,
                                                radii,
                                                XYZd,
                                                resolution,
                                                padding=0.0)
    volarr.shape = (XYZd[0], XYZd[1], XYZd[2])
    volarr = Numeric.ascontiguousarray(Numeric.transpose(volarr), 'f')

    weights = Numeric.ones(len(radii), 'f')
    h = {}
    from Volume.Grid3D import Grid3DF
    maskGrid = Grid3DF(volarr, origin, span, h)
    h['amin'], h['amax'], h['amean'], h['arms'] = maskGrid.stats()

    from UTpackages.UTisocontour import isocontour
    isocontour.setVerboseLevel(0)

    data = maskGrid.data

    origin = Numeric.array(maskGrid.origin).astype('f')
    stepsize = Numeric.array(maskGrid.stepSize).astype('f')

    if data.dtype.char != Numeric.float32:
        data = data.astype('f')  #Numeric.Float32)

    newgrid3D = Numeric.ascontiguousarray(
        Numeric.reshape(Numeric.transpose(data), (1, 1) + tuple(data.shape)),
        data.dtype.char)

    ndata = isocontour.newDatasetRegFloat3D(newgrid3D, origin, stepsize)

    isoc = isocontour.getContour3d(ndata, 0, 0, isovalue,
                                   isocontour.NO_COLOR_VARIABLE)
    vert = Numeric.zeros((isoc.nvert, 3)).astype('f')
    norm = Numeric.zeros((isoc.nvert, 3)).astype('f')
    col = Numeric.zeros((isoc.nvert)).astype('f')
    tri = Numeric.zeros((isoc.ntri, 3)).astype('i')

    isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)

    if maskGrid.crystal:
        vert = maskGrid.crystal.toCartesian(vert)

    return (vert, tri)