Esempio n. 1
0
 def __pow__(self, other):
     shape = self.array.shape
     if len(shape) != 2 or shape[0] != shape[1]:
         raise TypeError, "matrix is not square"
     if type(other) in (type(1), type(1L)):
         if other == 0:
             return Matrix(identity(shape[0]))
         if other < 0:
             result = Matrix(LinearAlgebra.inverse(self.array))
             x = Matrix(result)
             other = -other
         else:
             result = self
             x = result
         if other <= 3:
             while (other > 1):
                 result = result * x
                 other = other - 1
             return result
         # binary decomposition to reduce the number of Matrix
         #  Multiplies for other > 3.
         beta = _binary(other)
         t = len(beta)
         Z, q = x.copy(), 0
         while beta[t - q - 1] == '0':
             Z *= Z
             q += 1
         result = Z.copy()
         for k in range(q + 1, t):
             Z *= Z
             if beta[t - k - 1] == '1':
                 result *= Z
         return result
Esempio n. 2
0
 def __pow__(self, other):
     shape = self.array.shape
     if len(shape)!=2 or shape[0]!=shape[1]:
         raise TypeError, "matrix is not square"
     if type(other) in (type(1), type(1L)):
         if other==0:
             return Matrix(identity(shape[0]))
         if other<0:
             result=Matrix(LinearAlgebra.inverse(self.array))
             x=Matrix(result)
             other=-other
         else:
             result=self
             x=result
         if other <= 3:
             while(other>1):
                 result=result*x
                 other=other-1
             return result
         # binary decomposition to reduce the number of Matrix
         #  Multiplies for other > 3.
         beta = _binary(other)
         t = len(beta)
         Z,q = x.copy(),0
         while beta[t-q-1] == '0':
             Z *= Z
             q += 1
         result = Z.copy()
         for k in range(q+1,t):
             Z *= Z
             if beta[t-k-1] == '1':
                 result *= Z
         return result
     else:
         raise TypeError, "exponent must be an integer"
Esempio n. 3
0
def eigenvector_for_largest_eigenvalue(matrix):
    """Returns eigenvector corresponding to largest eigenvalue of matrix.
    
    Implements a numerical method for finding an eigenvector by repeated 
    application of the matrix to a starting vector. For a matrix A the 
    process w(k) <-- A*w(k-1) converges to eigenvector w with the largest 
    eigenvalue. Because distance matrix D has all entries >= 0, a theorem 
    due to Perron and Frobenius on nonnegative matrices guarantees good 
    behavior of this method, excepting degenerate cases where the 
    iteration oscillates. For distance matrices a remedy is to add the 
    identity matrix to A, permitting the iteration to converge to the 
    eigenvector. (From Sander and Schneider (1991), and Vingron and 
    Sibbald (1993)) 
    
    Note: Only works on square matrices.
    """
    #always add the identity matrix to avoid oscillating behavior
    matrix = matrix + identity(len(matrix))

    #v is a random vector (chosen as the normalized vector of ones)
    v = ones(len(matrix))/len(matrix)

    #iterate until convergence
    for i in range(1000):
        new_v = matrixmultiply(matrix,v)
        new_v = new_v/sum(new_v) #normalize
        if sum(map(abs,new_v-v)) > 1e-9:
            v = new_v #not converged yet
            continue
        else: #converged
            break
    
    return new_v
Esempio n. 4
0
 def rotate(self, angle):
   m = identity(3, typecode = Float)
   s = sin(angle)
   c = cos(angle)
   m[0, 0] =  c
   m[0, 1] = -s
   m[1, 0] =  s
   m[1, 1] =  c
   self.matrix = matrixmultiply(self.matrix, m)
Esempio n. 5
0
 def rotate(self, angle):
     m = identity(3, typecode=Float)
     s = sin(angle)
     c = cos(angle)
     m[0, 0] = c
     m[0, 1] = -s
     m[1, 0] = s
     m[1, 1] = c
     self.matrix = matrixmultiply(self.matrix, m)
Esempio n. 6
0
 def optimize(self):
     """Optimize the objective function with respect to varying params."""
     p, d = [], []
     for param in self.varyingParams:
         p.append(param.getValue())
         d.append(param.delta)
     p = array(p)
     d = identity(len(d)) * array(d,Float)
     return powell(self._objective, p, drxns=d)
	def AddPlane(self,origin):
		from Avatars.vtkGrid3D import vtkGrid3DPlane
		from Numeric import identity
		# Does the plane avatar already exist ?
		if hasattr(self,'plane'):
			# Yes, use it
			self.plane.SetOrigin(origin)
		else:	# No, add it
			normal=identity(3)[self.GetSTMTool().GetNormalAxis()]
			self.plane=vtkGrid3DPlane(normal,origin,vtkstructuredgrid=self.GetVTKData().GetvtkStructuredGrid(),parent=self)
			self.plane.SetColorTable(self.GetColorTable())
Esempio n. 8
0
	def AddPlane(self,origin):
		from Visualization.Avatars.vtkGrid3D import vtkGrid3DPlane
		from Numeric import identity
		# Does the plane avatar already exist ?
		if hasattr(self,'plane'):
			# Yes, use it
			self.plane.SetOrigin(origin)
		else:	# No, add it
			normal=identity(3)[self.GetSTMTool().GetNormalAxis()]
			self.plane=vtkGrid3DPlane(normal,origin,vtkstructuredgrid=self.GetVTKData().GetvtkStructuredGrid(),parent=self)
			self.plane.SetColorTable(self.GetColorTable())
Esempio n. 9
0
	def GetCoordinates(self):
		"""
		Returns a NumPy array with the scaled coordinates of the
		grid points. The array will have the shape, 
		(< *dim*>,< *N1* , *N2* ,..., *Ndim* >) where *dim* is the 
		dimension of the space.
		"""
		from ArrayTools import CoordinateArrayFromUnitVectors
		from Numeric import identity,Float
		
		shape=self.GetSpatialShape()
		gridunitcell=identity(len(shape)).astype(Float)/shape
		return CoordinateArrayFromUnitVectors(shape,gridunitcell)
Esempio n. 10
0
  def kfupdate(self, dt, rs):
    self.ab  = array((rs.ax, -rs.ay, -rs.az))

    ph = self.phi
    th = self.theta
    P  = self.pmat

    A  = array(((-rs.q*cos(ph)*tan(th)+rs.r*sin(ph)*tan(th), (-rs.q*sin(ph)+rs.r*cos(ph))/(cos(th)*cos(th))),
                (rs.q*sin(ph)-rs.r*cos(ph)                 , 0)))

    dph = rs.p - rs.q*sin(ph)*tan(th) - rs.r*cos(ph)*tan(th)
    dth =      - rs.q*cos(ph)         - rs.r*sin(ph)
    dP  = dot(A, P) + dot(P, transpose(A)) + self.Q

    ph = ph + dph * dt
    th = th + dth * dt
    P  = P  + dP  * dt

    Cx = array((0               , cos(th)))
    Cy = array((-cos(th)*cos(ph), sin(th)*sin(ph)))
    Cz = array((cos(th)*sin(ph) , sin(th)*cos(ph)))
    C  = array((Cx, Cy, Cz))

    L = dot(dot(P, transpose(C)), inverse(self.R + dot(dot(C, P), transpose(C))))
    h = array((sin(th), -cos(th)*sin(ph), -cos(th)*cos(ph)))

    P  = dot(identity(2) - dot(L, C), P)
    ph = ph + dot(L[0], self.ab - h)
    th = th + dot(L[1], self.ab - h) 

    ph = ((ph+pi) % (2*pi)) - pi;
    th = ((th+pi) % (2*pi)) - pi;

    self.pmat  = P
    self.phi   = ph 
    self.theta = th

    psidot = rs.q * sin(ph) / cos(th) + rs.r * cos(ph) / cos(th);
    self.psi += psidot * dt;

    self.quat = eul2quat(ph,th,self.psi)
    # self.dcmb2e = quat2dcm(quatinv(self.quat))

    # self.ae = dot(self.dcmb2e, self.ab)
    self.ae = quatrotate(quatinv(self.quat), self.ab)
    self.ae[2] = -self.ae[2]-1
    self.ae[1] = -self.ae[1]

    self.ve += self.ae * dt * 9.81
    self.xe += self.ve * dt
Esempio n. 11
0
            ymin = height*j/float(m)
            ymax = height*(j+1)/float(m)
            color = get_color(A[i,j],mina,maxa)
            if do_outline:
                draw.rectangle((xmin,ymin,xmax,ymax),fill=color,
                               outline=(0,0,0))
            else:
                draw.rectangle((xmin,ymin,xmax,ymax),fill=color)
                    
    img.save(fname)
    return

def get_color(a,cmin,cmax):
    """\
    Convert a float value to one of a continuous range of colors.
    Rewritten to use recipe 9.10 from the Python Cookbook.
    """
    import math
    try: a = float(a-cmin)/(cmax-cmin)
    except ZeroDivisionError: a=0.5 # cmax == cmin
    blue = min((max((4*(0.75-a),0.)),1.))
    red = min((max((4*(a-0.25),0.)),1.))
    green = min((max((4*math.fabs(a-0.5)-1.,0)),1.))
    return '#%1x%1x%1x' % (int(15*red),int(15*green),int(15*blue))

from Numeric import identity,Float

a = identity(10,Float)
spy_matrix_pil(a)
pcolor_matrix_pil(a,'tmp2.png')
Esempio n. 12
0
        maxa = A[0,0]
        for i in range(n):
            for j in range(m):
                mina = min(A[i,j], mina)
                maxa = max(A[i,j], maxa)

    if n>width or m>height:
        raise "Rectangle too big %d %d %d %d" % (n,m,width,height)
    for i in range(n):
        xmin = width*i/float(n)
        xmax = width*(i+1)/float(n)
        for j in range(m):
            ymin = height*j/float(m)
            ymax = height*(j+1)/float(m)
            color = colorfunc(A[i,j],mina,maxa)
            if do_outline:
                draw.rectangle((xmin,ymin,xmax,ymax),fill=color,
                               outline=(0,0,0))
            else:
                draw.rectangle((xmin,ymin,xmax,ymax),fill=color)
                    
    img.save(fname)
    return

if __name__ == "__main__":
    from Numeric import identity, Float

    a = identity(10,Float)
    spy_matrix_pil(a)
    pcolor_matrix_pil(a,'tmp2.png')
Esempio n. 13
0
 def reset(self):
   self.matrix = identity(3, typecode = Float)
Esempio n. 14
0
 def scale(self, sx, sy):
     m = identity(3, typecode=Float)
     m[0, 0] = sx
     m[1, 1] = sy
     self.matrix = matrixmultiply(self.matrix, m)
Esempio n. 15
0
 def reset(self):
     self.matrix = identity(3, typecode=Float)
Esempio n. 16
0
 def scale(self, sx, sy):
   m = identity(3, typecode = Float)
   m[0, 0] = sx
   m[1, 1] = sy
   self.matrix = matrixmultiply(self.matrix, m)
Esempio n. 17
0
import string