def inverse(self):
        "Returns the inverse of a rank-2 tensor."
	if self.rank == 2:
	    from LinearAlgebra import inverse
	    return Tensor(inverse(self.array))
	else:
	    raise ValueError, 'Undefined operation'
 def inverse(self):
     "Returns the inverse of a rank-2 tensor."
     if self.rank == 2:
         from LinearAlgebra import inverse
         return Tensor(inverse(self.array))
     else:
         raise ValueError, 'Undefined operation'
def spline(data, quality):
    """Interpolate a trajectory using natural cubic splines.

    Arguments:
        - data      a list or AMC object containing the data to be interpolated
        - quality   the number of new points to insert between data points
    """
    # Special case: The input data is an AMC object. For each bone in the AMC
    # object create a spline. Return an AMC object.
    if data.__class__ == AMC:
        interpolated = AMC()
        for bone, motion in data.bones.iteritems():
            interpolated.bones[bone] = spline(motion, quality)

        return interpolated

    data = Numeric.array(data)
    quality += 1
    # Assumming a 2-dimensional array.
    # FIXME - Needs error checking?
    length, dof = Numeric.shape(data)
    interpolated = Numeric.empty((length * quality, dof))

    # Range of times we'll be using for the vast majority of the splining process
    times = Numeric.arange(2, 3, 1. / quality)[:-1]

    # For calculating interpolated data points
    f = lambda c: lambda t: c[0] + c[1] * t + c[2] * t**2 + c[3] * t**3

    # Interpolate the data using chunks of the trajectory. Each chunk consists
    # of 4 points. Except for the first and last chunk, interpolate only the
    # inner 2 points of each chunk.
    for frame in range(length - 3):
        # Generate matrices and solve for the constants
        A, b = _getMatrix(data[frame:frame + 4], dof)
        Ainv = inverse(A)
        z = [Numeric.matrixmultiply(Ainv, x) for x in b]

        # Handle each degree of freedom individually
        for degree in range(dof):
            # At the beginning of the trajectory interpolate the first 2 points
            if frame == 0:
                smoothedFrame = frame * quality
                interpolated[smoothedFrame:smoothedFrame + quality, degree] = \
                        map(f(z[degree][:4]), Numeric.arange(1, 2, 1. / quality)[:-1])
            # At the end of the trajectory interpolate the last 2 points
            elif frame == length - 4:
                smoothedFrame = (frame + 2) * quality
                interpolated[smoothedFrame:smoothedFrame + quality, degree] = \
                        map(f(z[degree][-4:]), Numeric.arange(3, 4, 1. / quality)[:-1])

            # Interpolate the middle 2 points
            smoothedFrame = (frame + 1) * quality
            interpolated[smoothedFrame:smoothedFrame + quality, degree] = \
                    map(f(z[degree][4:8]), times)

    return interpolated
 def GetReciprocalBravaisLattice(self):
     from LinearAlgebra import inverse
     from Numeric import transpose, pi
     import copy
     reciprocal = copy.copy(self)
     # Using : rec=2pi*(unitcell^T)^-1
     recbasis = 2 * pi * inverse(transpose(self.GetBasis()))
     reciprocal.SetBasis(recbasis)
     return reciprocal
    def GetReciprocalBravaisLattice(self):
	from LinearAlgebra import inverse
	from Numeric import transpose,pi
	import copy
	reciprocal=copy.copy(self)
	# Using : rec=2pi*(unitcell^T)^-1
	recbasis=2*pi*inverse(transpose(self.GetBasis()))
	reciprocal.SetBasis(recbasis)
	return reciprocal
Exemple #6
0
def hermite(x0, x1, v0, v1, t):
    a = array([1, t, t**2, t**3])
    M = array([[1, 0, 0, 0],
               [1, 1, 1, 1],
               [0, 1, 0, 0],
               [0, 1, 2, 3]])
    p = transpose([[x0, x1, v0, v1]])

    return dot(dot(a, inverse(M)), p)
Exemple #7
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
Exemple #8
0
def bezier2(x0, p1, p2, x1, t):
    a = array([1, t, t**2, t**3])
    M = array([[1, 0, 0, 0],
               [1, 1, 1, 1],
               [0, 1, 0, 0],
               [0, 1, 2, 3]])
    B = array([[1, 0, 0, 0],
               [0, 0, 0, 1],
               [-3, 3, 0, 0],
               [0, 0, -3, 3]])
    p = transpose([[x0, p1, p2, x1]])

    C = dot(inverse(M), B)

    return dot(dot(a, C), p)
Exemple #9
0
def savitzky_golay(window_size=None,order=2):
    if window_size is None:
        window_size = order + 2

    if window_size % 2 != 1 or window_size < 1:
        raise TypeError("window size must be a positive odd number")
    if window_size < order + 2:
        raise TypeError("window size is too small for the polynomial")

    # A second order polynomial has 3 coefficients
    order_range = range(order+1)
    half_window = (window_size-1)//2
    B = array(
        [ [k**i for i in order_range] for k in range(-half_window, half_window+1)] )

    #           -1
    # [  T     ]      T
    # [ B  * B ]  *  B
    M = matrixmultiply(
           inverse(  matrixmultiply(transpose(B), B)),
           transpose(B)
           )
    return M
Exemple #10
0
def iagaussian(s,mu,sigma):
    """  o Purpose
      Generate a 2D Gaussian image.

  o Synopsis
      g = iagaussian(s,mu,sigma)

  o Input
      s: [rows columns]
    mu: Mean vector. 2D point (x;y). Point of maximum value.
    sigma: covariance matrix (square).  [ Sx^2 Sxy; Syx Sy^2]

  o Output
      g: 

  o Description
      A 2D Gaussian image is an image with a Gaussian distribution. It can be used to generate test patterns or Gaussian filters both for spatial and frequency domain. The integral of the gaussian function is 1.0.

  o Examples
      import Numeric
      f = iagaussian([8,4], [3,1], [[1,0],[0,1]])
      print Numeric.array2string(f, precision=4, suppress_small=1)
      g = ianormalize(f, [0,255]).astype(Numeric.UnsignedInt8)
      print g
    f = iagaussian(100, 50, 10*10)
      g = ianormalize(f, [0,1])
      g,d = iaplot(g)
      showfig(g)
    f = iagaussian([50,50], [25,10], [[10*10,0],[0,20*20]])
      g = ianormalize(f, [0,255]).astype(Numeric.UnsignedInt8)
      iashow(g)
"""
    from Numeric import asarray,product,arange,NewAxis,transpose,matrixmultiply,reshape,concatenate,resize,sum,zeros,Float,ravel,pi,sqrt,exp 
    from LinearAlgebra import inverse,determinant 
    
    if type(sigma).__name__ in ['int', 'float', 'complex']: sigma = [sigma]
    s, mu, sigma = asarray(s), asarray(mu), asarray(sigma)
    
    if (product(s) == max(s)):
        x = arange(product(s))
        d = x - mu
        if len(d.shape) == 1:
            tmp1 = d[:,NewAxis]
            tmp3 = d
        else:
            tmp1 = transpose(d)
            tmp3 = tmp1
        if len(sigma) == 1:
            tmp2 = 1./sigma
        else:
            tmp2 = inverse(sigma)
        k = matrixmultiply(tmp1, tmp2) * tmp3
    else:
        aux = arange(product(s))
        x, y = iaind2sub(s, aux)
        xx = reshape(concatenate((x,y)), (2, product(x.shape)))
    
        d = transpose(xx) - resize(reshape(mu,(len(mu),1)), (s[0]*s[1],len(mu)))
    
        if len(sigma) == 1:
            tmp = 1./sigma
        else:
            tmp = inverse(sigma)
        k = matrixmultiply(d, tmp) * d
        k = sum(transpose(k))
    
    g = zeros(s, Float)
    aux = ravel(g)
    if len(sigma) == 1:
        tmp = sigma
    else:
        tmp = determinant(sigma)
    aux[:] = 1./(2*pi*sqrt(tmp)) * exp(-1./2 * k)
    
    return g
Exemple #11
0
def vcross(a, b):
    return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]]

print "enter groove position"
g = readVector()
print "enter a"
a = readVector()
print "enter b"
b = readVector()

va = vsub(a, g)
vb = vsub(b, g)
vc = vcross(va, vb)

mat = array([[va[0], vb[0], vc[0]], [va[1], vb[1], vc[1]], [va[2], vb[2], vc[2]]])
inv = inverse(mat)

while (True):
    print "enter vector"
    v = readVector()
    vv = vsub(v, g)

    A = vv[0]*inv[0, 0] + vv[1]*inv[0, 1] + vv[2]*inv[0, 2]
    B = vv[0]*inv[1, 0] + vv[1]*inv[1, 1] + vv[2]*inv[1, 2]
    C = vv[0]*inv[2, 0] + vv[1]*inv[2, 1] + vv[2]*inv[2, 2]

    vcalc1 = vadd(vmulk(va, A), vmulk(vb, B))
    vcalc = vadd(vcalc1, vmulk(vc, C))
    delta = vsub(vv, vcalc)
    error = math.sqrt(vdot(delta, delta))
    delta2d = vsub(vv, vcalc1)
Exemple #12
0
def ACL(tree):
    """Returns a normalized dictionary of sequence weights {seq_id: weight}

    tree: a PhyloNode object

    The ACL method is named after Altschul, Carroll and Lipman, who published a 
    paper on sequence weighting in 1989.

    The ACL method is based on an idea of Felsenstein (1973). Imagine 
    electrical current flows from the root of the tree down the edges and 
    out the leaves. If the edge lengths are proportional to their electrical 
    resistances, current flowing out each leaf equals the leaf weight.

    The first step in the calculation of the weight vector is calculating a
    variance-covariance matrix. The variance of a leaf is proportional to the 
    distance from the root to that leaf. The covariance of two leaves is 
    proportional to the distance from the root to the last common ancestor 
    of the two leaves.

    The second step in the calculation results in a vector of weights. Suppose
    there are n leaves on the tree. Let i be the vector of size n, all of whose 
    elements are 1.0. The weight vector is calculated as:
    w = (inverse(M)*i)/(transpose(i)*inverse(M)*i)
    See Altschul 1989
    """
    #clip branch lengths to avoid error due to negative or zero branch lengths
    _clip_branch_lengths(tree)
    
    #get a list of sequence IDs (in the order that the tree will be traversed)
    seqs = []
    for n in tree.TerminalDescendants:
        seqs.append(n.Data)

    #initialize the variance-covariance matrix
    m = zeros([len(seqs),len(seqs)],Float64)

    #calculate (co)variances
    #variance of a node is defined as the distance from the root to the leaf
    #covariance of two nodes is defined as the distance from the root to the
    #last common ancestor of the two leaves. 
    for x in tree.TerminalDescendants:
        for y in tree.TerminalDescendants:
            idx_x = seqs.index(x.Data)
            idx_y = seqs.index(y.Data)
            if idx_x == idx_y:
                m[idx_x,idx_y] = x.distance(tree)
            else:
                lca = x.lastCommonAncestor(y)
                dist_lca_root = lca.distance(tree)
                m[idx_x,idx_y] = dist_lca_root
                m[idx_y,idx_x] = dist_lca_root

    #get the inverse of the variance-covariance matrix
    inv = inverse(m)
    #build vector i (vector or ones, length = # of leaves in the tree)
    i = ones(len(seqs),Float64)
    
    numerator = matrixmultiply(inv, i)
    denominator = matrixmultiply(matrixmultiply(transpose(i),inv),i)
    weight_vector = numerator/denominator

    #return a Weights object (is dict {seq_id: weight})
    return Weights(dict(zip(seqs,weight_vector)))
Exemple #13
0
import string