示例#1
0
def mfuncC(f, x):
    """
	mfuncC(f, x) : matrix function with possibly complex eigenvalues.
	Note: Numeric defines (v,u) = eig(x) => x*u.T = u.T * Diag(v)
	This function is needed by sqrtm and allows further functions.
	"""

    x = array(x)
    (v, u) = numerix.mlab.eig(x)
    uT = transpose(u)
    V = numerix.mlab.diag(f(v + 0j))
    y = matrixmultiply(uT, matrixmultiply(V, linear_algebra.inverse(uT)))
    return approx_real(y)
示例#2
0
def mfuncC(f, x):
	"""
	mfuncC(f, x) : matrix function with possibly complex eigenvalues.
	Note: Numeric defines (v,u) = eig(x) => x*u.T = u.T * Diag(v)
	This function is needed by sqrtm and allows further functions.
	"""
	
	x      = array(x) 
	(v, u) = numerix.mlab.eig(x)
	uT     = transpose(u)
	V      = numerix.mlab.diag(f(v+0j))
	y      = matrixmultiply(
           uT, matrixmultiply(
           V, linear_algebra.inverse(uT)))
	return approx_real(y)
示例#3
0
def view_transformation(E, R, V):
    n = (E - R)
    ## new
    #    n /= mod(n)
    #    u = nx.cross(V,n)
    #    u /= mod(u)
    #    v = nx.cross(n,u)
    #    Mr = nx.diag([1.]*4)
    #    Mt = nx.diag([1.]*4)
    #    Mr[:3,:3] = u,v,n
    #    Mt[:3,-1] = -E
    ## end new

    ## old
    n = n / mod(n)
    u = cross(V, n)
    u = u / mod(u)
    v = cross(n, u)
    Mr = [
        [u[0], u[1], u[2], 0],
        [v[0], v[1], v[2], 0],
        [n[0], n[1], n[2], 0],
        [0, 0, 0, 1],
    ]
    #
    Mt = [[1, 0, 0, -E[0]], [0, 1, 0, -E[1]], [0, 0, 1, -E[2]], [0, 0, 0, 1]]
    ## end old

    return nx.matrixmultiply(Mr, Mt)
示例#4
0
    def get_proj(self):
        """Create the projection matrix from the current viewing
        position.

        elev stores the elevation angle in the z plane
        azim stores the azimuth angle in the x,y plane

        dist is the distance of the eye viewing point from the object
        point.

        """
        relev,razim = nx.pi * self.elev/180, nx.pi * self.azim/180

        xmin,xmax = self.get_w_xlim()
        ymin,ymax = self.get_w_ylim()
        zmin,zmax = self.get_w_zlim()

        # transform to uniform world coordinates 0-1.0,0-1.0,0-1.0
        worldM = proj3d.world_transformation(xmin,xmax,
                                             ymin,ymax,
                                             zmin,zmax)

        # look into the middle of the new coordinates
        R = nx.array([0.5,0.5,0.5])
        #
        xp = R[0] + nx.cos(razim)*nx.cos(relev)*self.dist
        yp = R[1] + nx.sin(razim)*nx.cos(relev)*self.dist
        zp = R[2] + nx.sin(relev)*self.dist

        E = nx.array((xp, yp, zp))
        #
        self.eye = E
        self.vvec = R - E
        self.vvec = self.vvec / proj3d.mod(self.vvec)

        if abs(relev) > nx.pi/2:
            # upside down
            V = nx.array((0,0,-1))
        else:
            V = nx.array((0,0,1))
        zfront,zback = -self.dist,self.dist

        viewM = proj3d.view_transformation(E,R,V)
        perspM = proj3d.persp_transformation(zfront,zback)
        M0 = nx.matrixmultiply(viewM,worldM)
        M = nx.matrixmultiply(perspM,M0)
        return M
示例#5
0
def inv_transform(xs, ys, zs, M):
    iM = linear_algebra.inverse(M)
    vec = vec_pad_ones(xs, ys, zs)
    vecr = nx.matrixmultiply(iM, vec)
    try:
        vecr = vecr / vecr[3]
    except OverflowError:
        pass
    return vecr[0], vecr[1], vecr[2]
示例#6
0
def proj_transform_vec_clip(vec, M):
    vecw = nx.matrixmultiply(M, vec)
    w = vecw[3]
    # clip here..
    txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w
    tis = (vecw[0] >= 0) * (vecw[0] <= 1) * (vecw[1] >= 0) * (vecw[1] <= 1)
    if nx.sometrue(tis):
        tis = vecw[1] < 1
    return txs, tys, tzs, tis
示例#7
0
def test_proj_make_M(E=None):
    # eye point
    E = E or nx.array([1, -1, 2]) * 1000
    #E = nx.array([20,10,20])
    R = nx.array([1, 1, 1]) * 100
    V = nx.array([0, 0, 1])
    viewM = view_transformation(E, R, V)
    perspM = persp_transformation(100, -100)
    M = nx.matrixmultiply(perspM, viewM)
    return M
示例#8
0
 def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
     """Draws an arrow, starting at (x,y), direction and length
     given by (dx,dy) the width of the arrow is scaled by width
     """
     arrow = array([[0.0, 0.1], [0.0, -0.1], [0.8, -0.1], [0.8, -0.3], [1.0, 0.0], [0.8, 0.3], [0.8, 0.1]])
     L = sqrt(dx ** 2 + dy ** 2) or 1  # account for div by zero
     arrow[:, 0] *= L
     arrow[:, 1] *= width
     cx = float(dx) / L
     sx = float(dy) / L
     M = array([[cx, sx], [-sx, cx]])
     verts = matrixmultiply(arrow, M) + [x, y]
     Polygon.__init__(self, [tuple(t) for t in verts], **kwargs)
示例#9
0
 def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
     """Draws an arrow, starting at (x,y), direction and length
     given by (dx,dy) the width of the arrow is scaled by width
     """
     arrow = array([[0.0, 0.1], [0.0, -0.1], [0.8, -0.1], [0.8, -0.3],
                    [1.0, 0.0], [0.8, 0.3], [0.8, 0.1]])
     L = sqrt(dx**2 + dy**2) or 1  # account for div by zero
     arrow[:, 0] *= L
     arrow[:, 1] *= width
     cx = float(dx) / L
     sx = float(dy) / L
     M = array([[cx, sx], [-sx, cx]])
     verts = matrixmultiply(arrow, M) + [x, y]
     Polygon.__init__(self, [tuple(t) for t in verts], **kwargs)
示例#10
0
def norm(x, y=2):
    """
    Norm of a matrix or a vector according to Matlab.
    The description is taken from Matlab:
    
        For matrices...
          NORM(X) is the largest singular value of X, max(svd(X)).
          NORM(X,2) is the same as NORM(X).
          NORM(X,1) is the 1-norm of X, the largest column sum,
                          = max(sum(abs((X)))).
          NORM(X,inf) is the infinity norm of X, the largest row sum,
                          = max(sum(abs((X')))).
          NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).
          NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.
     
        For vectors...
          NORM(V,P) = sum(abs(V).^P)^(1/P).
          NORM(V) = norm(V,2).
          NORM(V,inf) = max(abs(V)).
          NORM(V,-inf) = min(abs(V)).
    """

    x = numerix.asarray(x)
    if MLab.rank(x) == 2:
        if y == 2:
            return MLab.max(MLab.svd(x)[1])
        elif y == 1:
            return MLab.max(MLab.sum(numerix.absolute((x))))
        elif y == 'inf':
            return MLab.max(MLab.sum(numerix.absolute((MLab.transpose(x)))))
        elif y == 'fro':
            return MLab.sqrt(
                MLab.sum(
                    MLab.diag(numerix.matrixmultiply(MLab.transpose(x), x))))
        else:
            verbose.report_error('Second argument not permitted for matrices')
            return None

    else:
        if y == 'inf':
            return MLab.max(numerix.absolute(x))
        elif y == '-inf':
            return MLab.min(numerix.absolute(x))
        else:
            return numerix.power(
                MLab.sum(numerix.power(numerix.absolute(x), y)), 1 / float(y))
示例#11
0
def norm(x,y=2):
    """
    Norm of a matrix or a vector according to Matlab.
    The description is taken from Matlab:
    
        For matrices...
          NORM(X) is the largest singular value of X, max(svd(X)).
          NORM(X,2) is the same as NORM(X).
          NORM(X,1) is the 1-norm of X, the largest column sum,
                          = max(sum(abs((X)))).
          NORM(X,inf) is the infinity norm of X, the largest row sum,
                          = max(sum(abs((X')))).
          NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).
          NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.
     
        For vectors...
          NORM(V,P) = sum(abs(V).^P)^(1/P).
          NORM(V) = norm(V,2).
          NORM(V,inf) = max(abs(V)).
          NORM(V,-inf) = min(abs(V)).
    """

    x = numerix.asarray(x)
    if MLab.rank(x)==2:
        if y==2:
            return MLab.max(MLab.svd(x)[1])
        elif y==1:
            return MLab.max(MLab.sum(numerix.absolute((x))))
        elif y=='inf':
            return MLab.max(MLab.sum(numerix.absolute((MLab.transpose(x)))))
        elif y=='fro':
            return MLab.sqrt(MLab.sum(MLab.diag(numerix.matrixmultiply(MLab.transpose(x),x))))
        else:
            verbose.report_error('Second argument not permitted for matrices')
            return None
        
    else:
        if y == 'inf':
            return MLab.max(numerix.absolute(x))
        elif y == '-inf':
            return MLab.min(numerix.absolute(x))
        else:
            return numerix.power(MLab.sum(numerix.power(numerix.absolute(x),y)),1/float(y))
示例#12
0
def polyval(p, x):
    """
    y = polyval(p,x)

    p is a vector of polynomial coeffients and y is the polynomial
    evaluated at x.

    Example code to remove a polynomial (quadratic) trend from y:

      p = polyfit(x, y, 2)
      trend = polyval(p, x)
      resid = y - trend

    See also polyfit
    
    """
    x = asarray(x) + 0.
    p = reshape(p, (len(p), 1))
    X = vander(x, len(p))
    y = matrixmultiply(X, p)
    return reshape(y, x.shape)
示例#13
0
def polyval(p,x):
    """
    y = polyval(p,x)

    p is a vector of polynomial coeffients and y is the polynomial
    evaluated at x.

    Example code to remove a polynomial (quadratic) trend from y:

      p = polyfit(x, y, 2)
      trend = polyval(p, x)
      resid = y - trend

    See also polyfit
    
    """
    x = asarray(x)+0.
    p = reshape(p, (len(p),1))
    X = vander(x,len(p))
    y =  matrixmultiply(X,p)
    return reshape(y, x.shape)
示例#14
0
def corrcoef(*args):
    """
    corrcoef(X) where X is a matrix returns a matrix of correlation
    coefficients for each numrows observations and numcols variables.
    
    corrcoef(x,y) where x and y are vectors returns the matrix or
    correlation coefficients for x and y.

    Numeric arrays can be real or complex

    The correlation matrix is defined from the covariance matrix C as

    r(i,j) = C[i,j] / sqrt(C[i,i]*C[j,j])
    """


    if len(args)==2:
        X = transpose(array([args[0]]+[args[1]]))
    elif len(args)==1:
        X = args[0]
    else:
        raise RuntimeError, 'Only expecting 1 or 2 arguments'

    
    C = cov(X)

    if len(args)==2:
       d = resize(diagonal(C), (2,1))
       denom = numerix.mlab.sqrt(matrixmultiply(d,transpose(d)))
    else:
       dc = diagonal(C)
       N = len(dc)       
       shape = N,N
       vi = resize(dc, shape)
       denom = numerix.mlab.sqrt(vi*transpose(vi)) # element wise multiplication
       

    r = divide(C,denom)
    try: return r.real
    except AttributeError: return r
示例#15
0
def corrcoef(*args):
    """
    corrcoef(X) where X is a matrix returns a matrix of correlation
    coefficients for each numrows observations and numcols variables.
    
    corrcoef(x,y) where x and y are vectors returns the matrix or
    correlation coefficients for x and y.

    Numeric arrays can be real or complex

    The correlation matrix is defined from the covariance matrix C as

    r(i,j) = C[i,j] / sqrt(C[i,i]*C[j,j])
    """

    if len(args) == 2:
        X = transpose(array([args[0]] + [args[1]]))
    elif len(args) == 1:
        X = args[0]
    else:
        raise RuntimeError, 'Only expecting 1 or 2 arguments'

    C = cov(X)

    if len(args) == 2:
        d = resize(diagonal(C), (2, 1))
        denom = numerix.mlab.sqrt(matrixmultiply(d, transpose(d)))
    else:
        dc = diagonal(C)
        N = len(dc)
        shape = N, N
        vi = resize(dc, shape)
        denom = numerix.mlab.sqrt(vi *
                                  transpose(vi))  # element wise multiplication

    r = divide(C, denom)
    try:
        return r.real
    except AttributeError:
        return r
示例#16
0
def prepca(P, frac=0):
    """
    Compute the principal components of P.  P is a numVars x
    numObservations numeric array.  frac is the minimum fraction of
    variance that a component must contain to be included

    Return value are
    Pcomponents : a num components x num observations numeric array
    Trans       : the weights matrix, ie, Pcomponents = Trans*P
    fracVar     : the fraction of the variance accounted for by each
                  component returned
    """
    U,s,v = svd(P)
    varEach = s**2/P.shape[1]
    totVar = asum(varEach)
    fracVar = divide(varEach,totVar)
    ind = int(asum(fracVar>=frac))

    # select the components that are greater
    Trans = transpose(U[:,:ind])
    # The transformed data
    Pcomponents = matrixmultiply(Trans,P)
    return Pcomponents, Trans, fracVar[:ind]
示例#17
0
def prepca(P, frac=0):
    """
    Compute the principal components of P.  P is a numVars x
    numObservations numeric array.  frac is the minimum fraction of
    variance that a component must contain to be included

    Return value are
    Pcomponents : a num components x num observations numeric array
    Trans       : the weights matrix, ie, Pcomponents = Trans*P
    fracVar     : the fraction of the variance accounted for by each
                  component returned
    """
    U, s, v = svd(P)
    varEach = s**2 / P.shape[1]
    totVar = asum(varEach)
    fracVar = divide(varEach, totVar)
    ind = int(asum(fracVar >= frac))

    # select the components that are greater
    Trans = transpose(U[:, :ind])
    # The transformed data
    Pcomponents = matrixmultiply(Trans, P)
    return Pcomponents, Trans, fracVar[:ind]
示例#18
0
def rot_x(V, alpha):
    cosa, sina = nx.cos(alpha), nx.sin(alpha)
    M1 = nx.array([[1, 0, 0, 0], [0, cosa, -sina, 0], [0, sina, cosa, 0],
                   [0, 0, 0, 0]])
    #
    return nx.matrixmultiply(M1, V)
示例#19
0
    def __init__(
        self,
        x,
        y,
        dx,
        dy,
        width=0.001,
        length_includes_head=False,
        head_width=None,
        head_length=None,
        shape="full",
        overhang=0,
        head_starts_at_zero=False,
        **kwargs
    ):
        """Returns a new Arrow.

        length_includes_head: True if head is counted in calculating the length.

        shape: ['full', 'left', 'right']

        overhang: distance that the arrow is swept back (0 overhang means
        triangular shape).

        head_starts_at_zero: if True, the head starts being drawn at coordinate
        0 instead of ending at coordinate 0.
        """
        if head_width is None:
            head_width = 3 * width
        if head_length is None:
            head_length = 1.5 * head_width

        distance = sqrt(dx ** 2 + dy ** 2)
        if length_includes_head:
            length = distance
        else:
            length = distance + head_length
        if not length:
            verts = []  # display nothing if empty
        else:
            # start by drawing horizontal arrow, point at (0,0)
            hw, hl, hs, lw = head_width, head_length, overhang, width
            left_half_arrow = array(
                [
                    [0.0, 0.0],  # tip
                    [-hl, -hw / 2.0],  # leftmost
                    [-hl * (1 - hs), -lw / 2.0],  # meets stem
                    [-length, -lw / 2.0],  # bottom left
                    [-length, 0],
                ]
            )
            # if we're not including the head, shift up by head length
            if not length_includes_head:
                left_half_arrow += [head_length, 0]
            # if the head starts at 0, shift up by another head length
            if head_starts_at_zero:
                left_half_arrow += [head_length / 2.0, 0]
            # figure out the shape, and complete accordingly
            if shape == "left":
                coords = left_half_arrow
            else:
                right_half_arrow = left_half_arrow * [1, -1]
                if shape == "right":
                    coords = right_half_arrow
                elif shape == "full":
                    coords = concatenate([left_half_arrow, right_half_arrow[::-1]])
                else:
                    raise ValueError, "Got unknown shape: %s" % shape
            cx = float(dx) / distance
            sx = float(dy) / distance
            M = array([[cx, sx], [-sx, cx]])
            verts = matrixmultiply(coords, M) + (x + dx, y + dy)

        Polygon.__init__(self, map(tuple, verts), **kwargs)
示例#20
0
    def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, \
        head_width=None, head_length=None, shape='full', overhang=0, \
        head_starts_at_zero=False,**kwargs):
        """Returns a new Arrow.

        length_includes_head: True if head is counted in calculating the length.

        shape: ['full', 'left', 'right']

        overhang: distance that the arrow is swept back (0 overhang means
        triangular shape).

        head_starts_at_zero: if True, the head starts being drawn at coordinate
        0 instead of ending at coordinate 0.
        """
        if head_width is None:
            head_width = 3 * width
        if head_length is None:
            head_length = 1.5 * head_width

        distance = sqrt(dx**2 + dy**2)
        if length_includes_head:
            length = distance
        else:
            length = distance + head_length
        if not length:
            verts = []  #display nothing if empty
        else:
            #start by drawing horizontal arrow, point at (0,0)
            hw, hl, hs, lw = head_width, head_length, overhang, width
            left_half_arrow = array([
                [0.0, 0.0],  #tip
                [-hl, -hw / 2.0],  #leftmost
                [-hl * (1 - hs), -lw / 2.0],  #meets stem
                [-length, -lw / 2.0],  #bottom left
                [-length, 0],
            ])
            #if we're not including the head, shift up by head length
            if not length_includes_head:
                left_half_arrow += [head_length, 0]
            #if the head starts at 0, shift up by another head length
            if head_starts_at_zero:
                left_half_arrow += [head_length / 2.0, 0]
            #figure out the shape, and complete accordingly
            if shape == 'left':
                coords = left_half_arrow
            else:
                right_half_arrow = left_half_arrow * [1, -1]
                if shape == 'right':
                    coords = right_half_arrow
                elif shape == 'full':
                    coords = concatenate(
                        [left_half_arrow, right_half_arrow[::-1]])
                else:
                    raise ValueError, "Got unknown shape: %s" % shape
            cx = float(dx) / distance
            sx = float(dy) / distance
            M = array([[cx, sx], [-sx, cx]])
            verts = matrixmultiply(coords, M) + (x + dx, y + dy)

        Polygon.__init__(self, map(tuple, verts), **kwargs)
示例#21
0
def proj_transform_vec(vec, M):
    vecw = nx.matrixmultiply(M, vec)
    w = vecw[3]
    # clip here..
    txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w
    return txs, tys, tzs