コード例 #1
0
def linePlaneIntersectionNumeric(p1, p2, p3, p4, p5):
  if not useNumeric:
    return linePlaneIntersection(p1, p2, p3, p4, p5)
  if useNumpy:
    top = [
        [1., 1., 1., 1.],
        [p1[0], p2[0], p3[0], p4[0]], [p1[1], p2[1], p3[1], p4[1]],
        [p1[2], p2[2], p3[2], p4[2]]]
    topDet = numpy.linalg.det(top)
    bottom = [
        [1., 1., 1., 0.], [p1[0], p2[0], p3[0], p5[0]-p4[0]],
        [p1[1], p2[1], p3[1], p5[1]-p4[1]], [p1[2], p2[2], p3[2], p5[2]-p4[2]]]
    botDet = numpy.linalg.det(bottom)
  else:  # actually use numeric
    top = Matrix.Matrix(
        [[1., 1., 1., 1.], [p1[0], p2[0], p3[0], p4[0]], [p1[1], p2[1],
         p3[1], p4[1]], [p1[2], p2[2], p3[2], p4[2]]])
    topDet = LinearAlgebra.determinant(top)
    bottom = Matrix.Matrix(
        [[1., 1., 1., 0.], [p1[0], p2[0], p3[0], p5[0]-p4[0]], [p1[1],
         p2[1], p3[1], p5[1]-p4[1]], [p1[2], p2[2], p3[2], p5[2]-p4[2]]])
    botDet = LinearAlgebra.determinant(bottom)
  if topDet == 0.0 or botDet == 0.0:
    return False
  t = -topDet/botDet
  x = p4[0] + (p5[0]-p4[0]) * t
  y = p4[1] + (p5[1]-p4[1]) * t
  z = p4[2] + (p5[2]-p4[2]) * t
  return [x, y, z]
コード例 #2
0
ファイル: ChargeFit.py プロジェクト: fxia22/ASM_xf
    def __init__(self, atoms, constraints):
	self.atoms = atoms
	natoms = len(self.atoms)
	nconst = reduce(operator.add, map(len, constraints))
	b = Numeric.zeros((nconst, natoms), Numeric.Float)
	c = Numeric.zeros((nconst,), Numeric.Float)
	i = 0
	for cons in constraints:
	    cons.setCoefficients(self.atoms, b, c, i)
	    i = i + len(cons)
	u, s, vt = LinearAlgebra.singular_value_decomposition(b)
	self.rank = 0
	for i in range(min(natoms, nconst)):
	    if s[i] > 0.:
		self.rank = self.rank + 1
	self.b = b
	self.bi = LinearAlgebra.generalized_inverse(b)
	self.p = Numeric.identity(natoms)-Numeric.dot(self.bi, self.b)
	self.c = c
	self.bi_c = Numeric.dot(self.bi, c)
	c_test = Numeric.dot(self.b, self.bi_c)
	if Numeric.add.reduce((c_test-c)**2)/nconst > 1.e-12:
	    Utility.warning("The charge constraints are inconsistent."
			    " They will be applied as a least-squares"
			    " condition.")
コード例 #3
0
ファイル: test.py プロジェクト: mikeswamp/numeric_copy
 def testgeneralizedInverse (self):
     "Test LinearAlgebra.generalized_inverse"
     import LinearAlgebra
     ca = Numeric.array([[1,1-1j],[0,1]])
     cai = LinearAlgebra.inverse(ca)
     cai2 = LinearAlgebra.generalized_inverse(ca)
     self.failUnless(eq(cai, cai2))
コード例 #4
0
ファイル: test.py プロジェクト: mikeswamp/numeric_copy
    def testLinearLeastSquares2(self):
        """
        From bug #503733. Failing with dlapack_lite
        """
        import LinearAlgebra
        d = [0.49910197] + [0.998203938] * 49
        d1 = [0.000898030454] * 50
        def tridiagonal(sz):
            G = Numeric.zeros((sz,sz), Numeric.Float64)
            for i in range(sz):
                G[i,i] = d[i]
            for i in range(0,sz-1):
                G[i+1,i] = G[i,i+1] = d1[i]
            return G

        yfull = Numeric.array(
            [4.37016668e+18, 4.09591905e+18, 3.82167167e+18, 4.12952660e+18,
             2.60084719e+18, 2.05944452e+18, 1.69850960e+18, 1.51450383e+18,
             1.39419275e+18, 1.25264986e+18, 1.18187857e+18, 1.16772440e+18,
             1.17126300e+18, 1.13941580e+18, 1.17834000e+18, 1.20664860e+18,
             1.18895580e+18, 1.18895580e+18, 1.21726440e+18, 1.24557296e+18,
             1.22434149e+18, 1.23495719e+18, 1.24203436e+18, 1.22434160e+18,
             1.23495720e+18, 1.21372580e+18, 1.22434160e+18, 1.21018740e+18,
             1.22080300e+18, 1.15357020e+18, 1.19957160e+18, 1.18187880e+18,
             1.19249440e+18, 1.18895579e+18, 1.28449704e+18, 1.27742021e+18,
             1.30218984e+18, 1.30926700e+18, 1.25972716e+18, 1.15003156e+18,
             1.17126296e+18, 1.15710876e+18, 1.10756882e+18, 1.20311006e+18,
             1.29511286e+18, 1.28449726e+18, 1.29157446e+18, 1.44373273e+18,])
        for i in range(20, 40):
            G = tridiagonal(i)
            y = yfull[:i]
            A = LinearAlgebra.linear_least_squares(G, y)[0]
            total = Numeric.add.reduce(y)
            residual = Numeric.absolute(y - Numeric.dot(G, A))
            assert_eq(0.0, Numeric.add.reduce(residual)/total)
コード例 #5
0
ファイル: Pass.py プロジェクト: szakats/bzflag_mirror
    def render(self, rstate):
        # Set up the texture matrix as the modelview inverse
        m = glGetFloatv(GL_MODELVIEW_MATRIX)
        glMatrixMode(GL_TEXTURE)
        m = LinearAlgebra.inverse(m)
        m[3][0] = 0
        m[3][1] = 0
        m[3][2] = 0
        glLoadMatrixf(m)
        glMatrixMode(GL_MODELVIEW)

        # Set up texture coordinate generation
        glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
        glTexGenfv(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_EXT)
        glTexGenfv(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_EXT)
        glTexGenfv(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_EXT)
        glEnable(GL_TEXTURE_GEN_S)
        glEnable(GL_TEXTURE_GEN_T)
        glEnable(GL_TEXTURE_GEN_R)

        # We're blending on top of existing polygons, so use the same tricks as the decal pass
        DecalRenderPass.render(self, rstate)

        # Clean up
        glMatrixMode(GL_TEXTURE)
        glLoadIdentity()
        glMatrixMode(GL_MODELVIEW)
        glDisable(GL_TEXTURE_GEN_S)
        glDisable(GL_TEXTURE_GEN_T)
        glDisable(GL_TEXTURE_GEN_R)
コード例 #6
0
ファイル: find_simple.py プロジェクト: yongwangCPH/peat
def plotit(xs,ys,title,legends):
    #
    # Do it 
    #
    num_points=0
    for x in xs:
        num_points=num_points+len(x)
    print num_points,'data points'
    #x=[1,2,3,4,5,6,7,8,9]
    #y=[2,4,6,8,10,12,14,16,18]
    mat_fix=[]
    vec_fix=[]
    for x in xs:
        for point in x:
            mat_fix.append([point,1.0])
    for y in ys:
        for point in y:
            vec_fix.append(point)
    import LinearAlgebra
    sols,rsq,rank,junk=LinearAlgebra.linear_least_squares(Numeric.array(mat_fix),
                                                          Numeric.array(vec_fix))
    slope=sols[0]
    intercept=sols[1]
    print rsq
    rsq=float(rsq[0])
    print 'Slope: %.2f, Intercept: %.2f, R^2: %.2f' %(slope,intercept,rsq)
    file=dislin_driver.graf_mult3(xs,ys,title,'Simple E','PBE_ene',legends)
    return
コード例 #7
0
ファイル: Matrix.py プロジェクト: IanReid/ABFGP
 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"
コード例 #8
0
ファイル: bigmat.py プロジェクト: 420peacemaker/roboto
def inversedot_woodbury(m, v):
    a = zeros((n, 11), Float)
    for i in range(n):
        for j in range(max(-7, -i), min(4, n - i)):
            a[i, j + 7] = m[i, i + j]
    print a
    al, indx, d = band.bandec(a, 7, 3)
    VtZ = identity(4, Float)
    Z = zeros((n, 4), Float)
    for i in range(4):
        u = zeros(n, Float)
        for j in range(4):
            u[j] = m[j, n - 4 + i]
        band.banbks(a, 7, 3, al, indx, u)
        for k in range(n):
            Z[k, i] = u[k]
        #Z[:,i] = u
        for j in range(4):
            VtZ[j, i] += u[n - 4 + j]
    print Z
    print VtZ
    H = la.inverse(VtZ)
    print H
    band.banbks(a, 7, 3, al, indx, v)
    return(v - dot(Z, dot(H, v[n - 4:])))
コード例 #9
0
ファイル: Transformation.py プロジェクト: fxia22/ASM_xf
    def screwMotion(self):
	import LinearAlgebra
	axis, angle = self.rotation().axisAndAngle()
	d = self.vector*axis
	x = d*axis-self.vector
	r0 = Numeric.dot(LinearAlgebra.generalized_inverse(
	                    self.tensor.array-Numeric.identity(3)), x.array)
	return VectorModule.Vector(r0), axis, angle, d
コード例 #10
0
ファイル: quaternion.py プロジェクト: MDAnalysis/pyQuteMol
 def inverse(self):
     """
     @returns: the inverse
     @rtype: L{quaternion}
     """
     import LinearAlgebra
     inverse = LinearAlgebra.inverse(self.asMatrix())
     return quaternion(inverse[:, 0])
コード例 #11
0
ファイル: bigmat.py プロジェクト: 420peacemaker/roboto
def inversedot(m, v):
    return dot(la.inverse(m), v)
    n, nn = m.shape
    if 1:
        for i in range(n):
            sys.stdout.write('% ')
            for j in range(n):
                if m[i, j] > 0: sys.stdout.write('+ ')
                elif m[i, j] < 0: sys.stdout.write('- ')
                else: sys.stdout.write('  ')
            sys.stdout.write('\n')

    cyclic = False
    for i in range(4):
        for j in range(n - 4, n):
            if m[i, j] != 0:
                cyclic = True
    print '% cyclic:', cyclic
    if not cyclic:
        a = zeros((n, 11), Float)
        for i in range(n):
            for j in range(max(-5, -i), min(6, n - i)):
                a[i, j + 5] = m[i, i + j]
        for i in range(n):
            sys.stdout.write('% ')
            for j in range(11):
                if a[i, j] > 0: sys.stdout.write('+ ')
                elif a[i, j] < 0: sys.stdout.write('- ')
                else: sys.stdout.write('  ')
            sys.stdout.write('\n')
        al, indx, d = band.bandec(a, 5, 5)
        print a
        band.banbks(a, 5, 5, al, indx, v)
        return v
    else:
        #return inversedot_woodbury(m, v)
        bign = 3 * n
        a = zeros((bign, 11), Float)
        u = zeros(bign, Float)
        for i in range(bign):
            u[i] = v[i % n]
            for j in range(-7, 4):
                a[i, j + 7] = m[i % n, (i + j + 7 * n) % n]
        #print a
        if 1:
            for i in range(bign):
                sys.stdout.write('% ')
                for j in range(11):
                    if a[i, j] > 0: sys.stdout.write('+ ')
                    elif a[i, j] < 0: sys.stdout.write('- ')
                    else: sys.stdout.write('  ')
                sys.stdout.write('\n')
        #print u
        al, indx, d = band.bandec(a, 5, 5)
        band.banbks(a, 5, 5, al, indx, u)
        #print u
        return u[n + 2: 2 * n + 2]
コード例 #12
0
ファイル: test.py プロジェクト: mikeswamp/numeric_copy
 def testEigenvalues(self):
     """
     From bug #545259 -- illegal value to DGEEV routine
     """
     import LinearAlgebra
     a = Numeric.array([[2,3], [4,5]])
     v = LinearAlgebra.eigenvalues(a)
     assert_eq(v, Numeric.array([3.5-math.sqrt(57)/2.,
                                 3.5+math.sqrt(57)/2.]))
コード例 #13
0
ファイル: test.py プロジェクト: mikeswamp/numeric_copy
 def testHeigenvalues(self):
     """
     From bug #464980.
     """
     import LinearAlgebra
     a = Numeric.array([[1.0, 0.01j], [-0.01j, 1.0]])
     v = LinearAlgebra.eigenvalues(a)
     assert_eq(v, [1.01+0.j, 0.99+0.j])
     Hv = LinearAlgebra.Heigenvalues(a)
     assert_eq(v, [1.01+0.j, 0.99+0.j])
コード例 #14
0
ファイル: kabsch.py プロジェクト: svensken/octathorp
	def calcEigenPairs( self, RtR ):
		"""
		Calculate the corresponding eigenpairs for RtR, and sort them accordingly:
		M{m1 >= m2 >= m3}; set M{v3 = v1 x v2} to ensure a RHS
		(CORRECT)
		
		@postcondition: The eigen pairs are calculated, sorted such that M{m1 >= m2 >= m3} and
		M{v3 = v1 x v2}.
		
		@param RtR: 3x3 Matrix of M{R^t * R}.
		@type  RtR: 3x3 Matrix
		@return : Eigenpairs for the RtR matrix.
		@rtype  : List of stuff
		
		"""
		
		eVal, eVec = LinearAlgebra.eigenvectors(RtR)

		# This is cool.  We sort it using Numeric.sort(eVal)
		# then we reverse it using nifty-crazy ass notation [::-1].
		eVal2 = Numeric.sort(eVal)[::-1]
		eVec2 = [[],[],[]] #Numeric.zeros((3,3), Numeric.Float64)
				
		# Map the vectors to their appropriate owners		
		if ( eVal2[0] == eVal[0]):
			eVec2[0] = eVec[0]
			if ( eVal2[1] == eVal[1] ):
				eVec2[1] = eVec[1]
				eVec2[2] = eVec[2]
			else:
				eVec2[1] = eVec[2]
				eVec2[2] = eVec[1]
		elif( eVal2[0] == eVal[1]):
			eVec2[0] = eVec[1]
			if ( eVal2[1] == eVal[0] ):
				eVec2[1] = eVec[0]
				eVec2[2] = eVec[2]
			else:
				eVec2[1] = eVec[2]
				eVec2[2] = eVec[0]
		elif( eVal2[0] == eVal[2]):
			eVec2[0] = eVec[2]
			if ( eVal2[1] == eVal[1] ):
				eVec2[1] = eVec[1]
				eVec2[2] = eVec[0]
			else:
				eVec2[1] = eVec[0]
				eVec2[2] = eVec[1]

		eVec2[2][0] = eVec2[0][1]*eVec2[1][2] - eVec2[0][2]*eVec2[1][1]
		eVec2[2][1] = eVec2[0][2]*eVec2[1][0] - eVec2[0][0]*eVec2[1][2]
		eVec2[2][2] = eVec2[0][0]*eVec2[1][1] - eVec2[0][1]*eVec2[1][0]
		
		return [eVal2, eVec2]
コード例 #15
0
ファイル: linalg.py プロジェクト: alexei-matveev/ccp1gui
def eig(object,**kw):
    """We try to adhere to the numpy way of doing things, so we need to do a transpose on the results
    that we get back from Numeric"""
    global _LinearAlgebra, _numpy_linalg
    if _LinearAlgebra:
        eigval,eigvec =  _LinearAlgebra.eigenvectors(object,**kw)
        eigvec = objects.numeric.transpose(eigvec)
        return eigval,eigvec
    elif _numpy_linalg:
        return _numpy_linalg.eig(object,**kw)
    else:
        raise AttributeError("No linear algebra functionality to deal with an eigenvectors.")
コード例 #16
0
ファイル: test.py プロジェクト: mikeswamp/numeric_copy
 def testLinearLeastSquares(self):
     """
     From bug #503733.
     """
     # XXX not positive on this yet
     import LinearAlgebra
     from RandomArray import seed, random
     seed(7,19)
     (n, m) = (180, 35)
     yp = random((n,m))
     y  = random(n)
     x, residuals, rank, sv = LinearAlgebra.linear_least_squares(yp, y)
     # shouldn't segfault.
     assert rank == m
コード例 #17
0
def fit_polynomial(x_vector, data_vector):
    """Fit a polynomial of degree `degree' at the points 
    in `x_vector' to the `data_vector' by interpolation.
    """

    import Numeric as num
    import LinearAlgebra as la

    degree = len(x_vector)-1

    vdm = vandermonde(x_vector, degree)
    result = la.solve_linear_equations(vdm, num.array(data_vector))
    result = list(result)
    result.reverse()
    return Polynomial(result)
コード例 #18
0
def main():

    import Numeric, LinearAlgebra
    import sys
    sys.path.append('/home/people/tc/svn/tc_sandbox/misc/rmsf_nmr.py')
    import rmsf_nmr

    pdb = '1e8l'
    chain = 'A'
    model1 = 1
    model2 = 2

    d_coordinates = rmsf_nmr.parse_coordinates(
        pdb,
        chain,
    )

    vector_difference = calculate_difference_vector(
        d_coordinates,
        model1,
        model2,
    )

    l_coordinates = d_coordinates[1]
    matrix_hessian = rmsf_nmr.calculate_hessian_matrix(l_coordinates)

    l_eigenvectors = rmsf_nmr.calculate_eigenvectors(matrix_hessian)

    l_eigenvectors_transposed = transpose_rows_and_columns(l_eigenvectors)

    vector_difference = Numeric.array(vector_difference)
    l_contributions = LinearAlgebra.solve_linear_equations(
        l_eigenvectors_transposed, vector_difference)

    fd = open('contrib_%s_%s.tmp' % (model1, model2), 'w')
    fd.close()
    for i in range(len(l_contributions)):
        ##        print i, vector[i]
        fd = open('contrib_%s_%s.tmp' % (model1, model2), 'a')
        fd.write('%s %s\n' % (i + 1, l_contributions[i]))
        fd.close()

    fo = 'cumoverlap_%s_%s.tmp' % (model1, model2)
    mode_min = 6
    calculate_cumulated_overlap(fo, l_contributions, vector_difference,
                                l_eigenvectors, mode_min)

    return
コード例 #19
0
ファイル: Collection.py プロジェクト: fxia22/ASM_xf
    def findTransformationAsQuaternion(self, conf1, conf2 = None):
	if conf2 is None:
	    conf1, conf2 = conf2, conf1
        ref = conf1
        conf = conf2
        weights = self.universe().masses()
        weights = weights/self.mass()
        ref_cms = self.centerOfMass(ref).array
        pos = Numeric.zeros((3,), Numeric.Float)
        possq = 0.
        cross = Numeric.zeros((3, 3), Numeric.Float)
        for a in self.atomList():
            r = a.position(conf).array
            r_ref = a.position(ref).array-ref_cms
            w = weights[a]
            pos = pos + w*r
            possq = possq + w*Numeric.add.reduce(r*r) \
                          + w*Numeric.add.reduce(r_ref*r_ref)
            cross = cross + w*r[:, Numeric.NewAxis]*r_ref[Numeric.NewAxis, :]
        k = Numeric.zeros((4, 4), Numeric.Float)
        k[0, 0] = -cross[0, 0]-cross[1, 1]-cross[2, 2]
        k[0, 1] = cross[1, 2]-cross[2, 1]
        k[0, 2] = cross[2, 0]-cross[0, 2]
        k[0, 3] = cross[0, 1]-cross[1, 0]
        k[1, 1] = -cross[0, 0]+cross[1, 1]+cross[2, 2]
        k[1, 2] = -cross[0, 1]-cross[1, 0]
        k[1, 3] = -cross[0, 2]-cross[2, 0]
        k[2, 2] = cross[0, 0]-cross[1, 1]+cross[2, 2]
        k[2, 3] = -cross[1, 2]-cross[2, 1]
        k[3, 3] = cross[0, 0]+cross[1, 1]-cross[2, 2]
        for i in range(1, 4):
            for j in range(i):
                k[i, j] = k[j, i]
        k = 2.*k
        for i in range(4):
            k[i, i] = k[i, i] + possq - Numeric.add.reduce(pos*pos)
	import LinearAlgebra
	e, v = LinearAlgebra.eigenvectors(k)
	i = Numeric.argmin(e)
        v = v[i]
        if v[0] < 0: v = -v
	if e[i] <= 0.:
	    rms = 0.
	else:
	    rms = Numeric.sqrt(e[i])
        return Quaternion.Quaternion(v), Vector(ref_cms), \
               Vector(pos), rms
コード例 #20
0
ファイル: RandomArray.py プロジェクト: KarolNi/VROOM-
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 1 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.shape[0]).
          In this case, output[i,j,...,:] is a 1-D array containing a multivariate
          normal."""
    # Check preconditions on arguments
    mean = Numeric.array(mean)
    cov = Numeric.array(cov)
    if len(mean.shape) != 1:
        raise ArgumentError, "mean must be 1 dimensional."
    if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]):
        raise ArgumentError, "cov must be 2 dimensional and square."
    if mean.shape[0] != cov.shape[0]:
        raise ArgumentError, "mean and cov must have same length."
    # Compute shape of output
    if isinstance(shape, IntType): shape = [shape]
    final_shape = list(shape[:])
    final_shape.append(mean.shape[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(Numeric.multiply.reduce(final_shape))
    x.shape = (Numeric.multiply.reduce(final_shape[0:len(final_shape) - 1]),
               mean.shape[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) = LinearAlgebra.singular_value_decomposition(cov)
    x = Numeric.matrixmultiply(x * Numeric.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.
    Numeric.add(mean, x, x)
    x.shape = final_shape
    return x
コード例 #21
0
ファイル: NMA_vs_ED.py プロジェクト: tommycarstensen/sandbox
def diagonalization(matrix):

    import LinearAlgebra

    eigen_tuple = LinearAlgebra.Heigenvectors(matrix)
    ## parse eigenvalues and eigenvectors
    eigenvalues = list(eigen_tuple[0])
    eigenvectors = list(eigen_tuple[1])
    ## organize eigenvalues and eigenvectors in list
    eigen_list = zip(eigenvalues, eigenvectors)
    ## sort list
    eigen_list.sort()
    ## parse sorted eigenvalues and eigenvectors
    eigenvalues = [eigen_list[eigen][0] for eigen in range(len(eigen_list))]
    eigenvectors = [eigen_list[eigen][1] for eigen in range(len(eigen_list))]

    return eigenvalues, eigenvectors
コード例 #22
0
ファイル: RandomArray.py プロジェクト: tomaszpg/PogodaTMC
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 1 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.shape[0]).
          In this case, output[i,j,...,:] is a 1-D array containing a multivariate
          normal."""
       # Check preconditions on arguments
       mean = Numeric.array(mean)
       cov = Numeric.array(cov)
       if len(mean.shape) != 1:
              raise ArgumentError, "mean must be 1 dimensional."
       if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]):
              raise ArgumentError, "cov must be 2 dimensional and square."
       if mean.shape[0] != cov.shape[0]:
              raise ArgumentError, "mean and cov must have same length."
       # Compute shape of output
       if isinstance(shape, IntType): shape = [shape]
       final_shape = list(shape[:])
       final_shape.append(mean.shape[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(Numeric.multiply.reduce(final_shape))
       x.shape = (Numeric.multiply.reduce(final_shape[0:len(final_shape)-1]),
                  mean.shape[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) = LinearAlgebra.singular_value_decomposition(cov)
       x = Numeric.matrixmultiply(x*Numeric.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.
       Numeric.add(mean,x,x)
       x.shape = final_shape
       return x
コード例 #23
0
def calculate_eigenvectors(matrix_hessian):

    import LinearAlgebra
    ## diagonalize hessian matrix
    eigen_tuple = LinearAlgebra.Heigenvectors(matrix_hessian)
    ## parse eigenvalues and eigenvectors
    eigenvalues = list(eigen_tuple[0])
    eigenvectors = list(eigen_tuple[1])
    ## organize eigenvalues and eigenvectors in list
    eigen_list = zip(eigenvalues, eigenvectors)
    ## sort list
    eigen_list.sort()
    ## parse sorted eigenvalues and eigenvectors
    eigenvalues = [eigen_list[eigen][0] for eigen in range(len(eigen_list))]
    eigenvectors = [eigen_list[eigen][1] for eigen in range(len(eigen_list))]

    return eigenvectors
コード例 #24
0
ファイル: pca.py プロジェクト: ChrisX34/stuff
 def compute(self):
     N = len(self.points)
     Ninv = 1. / N
     # get the mean, and deviations from the mean
     mu = Ninv * self.mu
     devs = map(lambda pt,mu=mu: pt - mu, self.points)
     # get a covariance matrix
     C = Numeric.zeros((DIMENSIONS, DIMENSIONS))
     for x in devs:
         C = C + Numeric.matrixmultiply(x,
                                        Numeric.transpose(x))
     C = Ninv * C
     # sort eigenvalue/vector pairs in order of decreasing eigenvalue
     evals, V = LinearAlgebra.eigenvectors(C)
     pairs = map(None, evals, V)
     pairs.sort(lambda x, y: cmp(y, x))
     self.eigenvalues = map(lambda p: p[0], pairs)
     A = Numeric.array(map(lambda x: x[1], pairs))
     self.A = Numeric.transpose(A)
コード例 #25
0
ファイル: Matrix.py プロジェクト: IanReid/ABFGP
 def __getattr__(self, attr):
     if attr == 'A':
         return squeeze(self.array)
     elif attr == 'T':
         return Matrix(Numeric.transpose(self.array))
     elif attr == 'H':
         if len(self.array.shape) == 1:
             self.array.shape = (1,self.array.shape[0])
         return Matrix(Numeric.conjugate(Numeric.transpose(self.array)))
     elif attr == 'I':
         return Matrix(LinearAlgebra.inverse(self.array))
     elif attr == 'real':
         return Matrix(self.array.real)
     elif attr == 'imag':
         return Matrix(self.array.imag)
     elif attr == 'flat':
         return Matrix(self.array.flat)
     else:
         raise AttributeError, attr + " not found."
コード例 #26
0
ファイル: Matrix.py プロジェクト: KarolNi/VROOM-
 def __getattr__(self, attr):
     if attr == 'A':
         return squeeze(self.array)
     elif attr == 'T':
         return Matrix(Numeric.transpose(self.array))
     elif attr == 'H':
         if len(self.array.shape) == 1:
             self.array.shape = (1, self.array.shape[0])
         return Matrix(Numeric.conjugate(Numeric.transpose(self.array)))
     elif attr == 'I':
         return Matrix(LinearAlgebra.inverse(self.array))
     elif attr == 'real':
         return Matrix(self.array.real)
     elif attr == 'imag':
         return Matrix(self.array.imag)
     elif attr == 'flat':
         return Matrix(self.array.flat)
     else:
         raise AttributeError, attr + " not found."
コード例 #27
0
ファイル: test.py プロジェクト: mikeswamp/numeric_copy
 def testSVD(self):
     """
     From bug #930735. Numbers redone in Maple.
     """
     import LinearAlgebra
     a = Numeric.array([[2,4],[1,3],[0,0],[0,0]])
     u, s, vt = LinearAlgebra.singular_value_decomposition(a)
     s34d2 = math.sqrt(34.)/2
     s26d2 = math.sqrt(26.)/2
     assert_eq(s, Numeric.array([s34d2+s26d2, s34d2-s26d2]))
     vt_c = Numeric.array([[-0.404553584833756919, -0.914514295677304467],
                           [-0.914514295677304467,  0.404553584833756919]])
     assert_eq(vt, vt_c)
     u_c = Numeric.array([[-0.817415560470363233, -0.576048436766320782],
                          [-0.576048436766320782,  0.817415560470363344],
                          [0, 0],
                          [0, 0]])
     assert_eq(u, u_c)
     assert_eq(a, Numeric.dot(u*s, vt))
コード例 #28
0
 def findUnitEigenvector(self):
     import LinearAlgebra
     evecs = LinearAlgebra.eigenvectors(self.matrix)
     self.eigenValues = evecs[0]
     self.eigenVectors = evecs[1]
     closest = -1
     best = 1.0E+10
     for i in range(self.dimension):
         sep = abs(self.eigenValues[i] - 1)
         if sep < best:
             best = sep
             closest = i
     e = self.eigenVectors[closest]
     self.unitEigenvalue = self.eigenValues[closest]
     sum = 0.0
     for i in range(self.dimension):
         sum += e[i]
     for j in range(self.dimension):
         e[j] /= sum
     self.unitEigenvector = e
コード例 #29
0
ファイル: pca.py プロジェクト: tommycarstensen/sandbox
def diagonalization(matrix):

    print 'diagonalizing %sx%s matrix' %(len(matrix),len(matrix))

    import LinearAlgebra

    eigen_tuple = LinearAlgebra.eigenvectors(matrix)
    ## parse eigenvalues and eigenvectors
    eigenvalues = list(eigen_tuple[0])
    eigenvectors = list(eigen_tuple[1])
    ## organize eigenvalues and eigenvectors in list
    eigen_list = zip(eigenvalues, eigenvectors)
    ## sort list
    eigen_list.sort()
    ## reverse list
    eigen_list.reverse()
    ## parse sorted eigenvalues and eigenvectors
    eigenvalues = [eigen_list[eigen][0] for eigen in range(len(eigen_list))]
    eigenvectors = [eigen_list[eigen][1] for eigen in range(len(eigen_list))]

    return eigenvalues, eigenvectors
コード例 #30
0
ファイル: BoxMinimizer.py プロジェクト: AKrishnachand/n2dm
    def ComputeComplianceMatrix(self):
        print "In BoxMinimizer.ComputeComplianceMatrix"
        bm = self.bulkModulus
        mu = self.shearModulus
        Lambda = bm - (2. / 3) * mu

        ecMatrix = num.zeros((6, 6), num.Float)

        for idx in xrange(0, 3):
            ecMatrix[idx, idx] = Lambda + 2 * mu

        ecMatrix[0, 1] = Lambda
        ecMatrix[1, 0] = Lambda
        ecMatrix[0, 2] = Lambda
        ecMatrix[2, 0] = Lambda
        ecMatrix[1, 2] = Lambda
        ecMatrix[2, 1] = Lambda
        for idx in xrange(3, 6):
            ecMatrix[idx, idx] = mu

        self.compliance = LA.inverse(ecMatrix)
コード例 #31
0
ファイル: BoxMinimizer.py プロジェクト: auag92/n2dm
    def ComputeComplianceMatrix(self):
        print "In BoxMinimizer.ComputeComplianceMatrix"
        bm = self.bulkModulus
        mu = self.shearModulus
        Lambda = bm - (2./3) * mu

        ecMatrix = num.zeros((6,6),num.Float)

        for idx in xrange(0,3):
            ecMatrix[idx, idx] = Lambda + 2*mu

        ecMatrix[0,1] = Lambda
        ecMatrix[1,0] = Lambda
        ecMatrix[0,2] = Lambda
        ecMatrix[2,0] = Lambda
        ecMatrix[1,2] = Lambda
        ecMatrix[2,1] = Lambda
        for idx in xrange(3,6):
            ecMatrix[idx, idx] = mu


        self.compliance = LA.inverse(ecMatrix)
コード例 #32
0
def main():

    import Numeric,LinearAlgebra
    import sys
    sys.path.append('/home/people/tc/svn/tc_sandbox/misc/rmsf_nmr.py')
    import rmsf_nmr

    pdb = '1e8l'
    chain = 'A'
    model1 = 1
    model2 = 2

    d_coordinates = rmsf_nmr.parse_coordinates(pdb,chain,)

    vector_difference = calculate_difference_vector(d_coordinates,model1,model2,)

    l_coordinates = d_coordinates[1]
    matrix_hessian = rmsf_nmr.calculate_hessian_matrix(l_coordinates)

    l_eigenvectors = rmsf_nmr.calculate_eigenvectors(matrix_hessian)

    l_eigenvectors_transposed = transpose_rows_and_columns(l_eigenvectors)

    vector_difference = Numeric.array(vector_difference)
    l_contributions = LinearAlgebra.solve_linear_equations(l_eigenvectors_transposed,vector_difference)

    fd = open('contrib_%s_%s.tmp' %(model1,model2),'w')
    fd.close()
    for i in range(len(l_contributions)):
##        print i, vector[i]
        fd = open('contrib_%s_%s.tmp' %(model1,model2),'a')
        fd.write('%s %s\n' %(i+1,l_contributions[i]))
        fd.close()

    fo = 'cumoverlap_%s_%s.tmp' %(model1,model2)
    mode_min = 6
    calculate_cumulated_overlap(fo,l_contributions,vector_difference,l_eigenvectors,mode_min)

    return
コード例 #33
0
ファイル: Polynomial.py プロジェクト: fxia22/ASM_xf
def fitPolynomial(order, points, values):
    if len(points) != len(values):
	raise ValueError, 'Inconsistent arguments'
    if type(order) != type(()):
	order = (order,)
    order = tuple(map(lambda n: n+1, order))
    if not _isSequence(points[0]):
	points = map(lambda p: (p,), points)
    if len(order) != len(points[0]):
	raise ValueError, 'Inconsistent arguments'
    if Numeric.multiply.reduce(order) > len(points):
	raise ValueError, 'Not enough points'
    matrix = []
    for p in points:
	matrix.append(Numeric.ravel(_powers(p, order)))
    matrix = Numeric.array(matrix)
    values = Numeric.array(values)
    #inv = LinearAlgebra.generalized_inverse(matrix)
    #coeff = Numeric.dot(inv, values)
    coeff = LinearAlgebra.linear_least_squares(matrix, values)[0]
    coeff = Numeric.reshape(coeff, order)
    return Polynomial(coeff)
コード例 #34
0
def fitPolynomial(order, points, values):
    if len(points) != len(values):
	raise ValueError, 'Inconsistent arguments'
    if type(order) != type(()):
	order = (order,)
    order = tuple(map(lambda n: n+1, order))
    if not _isSequence(points[0]):
	points = map(lambda p: (p,), points)
    if len(order) != len(points[0]):
	raise ValueError, 'Inconsistent arguments'
    if Numeric.multiply.reduce(order) > len(points):
	raise ValueError, 'Not enough points'
    matrix = []
    for p in points:
	matrix.append(Numeric.ravel(_powers(p, order)))
    matrix = Numeric.array(matrix)
    values = Numeric.array(values)
    inv = LinearAlgebra.generalized_inverse(matrix)
    coeff = Numeric.dot(inv, values)
    #coeff = LinearAlgebra.linear_least_squares(matrix, values)[0]
    coeff = Numeric.reshape(coeff, order)
    return Polynomial(coeff)
コード例 #35
0
def getHeight(x, y, z):
    ''' Calculates the height of a point from the Earth's surface given that point's position.

		Arguments:
			x: [float] X coordinate of the 3D position (m).
			y: [float] Y coordinate of the 3D position (m).
			z: [float] Z coordinate of the 3D position (m).

		Returns:
			h: [float] Height of the object from the Earth's surface. (m)
	'''

    # Get latitude of a given position
    lat = cartesianToGeodetic(x, y, z)[0]

    # Get the radius of the Earth
    earth_radius = geocentricR(lat)
    radius = linalg.originDist(x, y, z)

    height = radius - earth_radius

    return height
コード例 #36
0
ファイル: BoxMinimizer.py プロジェクト: AKrishnachand/n2dm
    def EnergyFromBoxShape(self, strain):
        if self.atoms == None:
            return

        if self.debug:
            unstrainedEnergy = self.atoms.GetPotentialEnergy()

        unstrainedSCVs = ApplyStrain(self.atoms, strain)

        if self.debug >= 2:
            print "volume:", LA.determinant(self.atoms.GetUnitCell())

        energy = self.atoms.GetPotentialEnergy()

        # restore original state
        self.atoms.GetUnitCell().SetBasis(unstrainedSCVs)

        if self.debug:
            if abs(unstrainedEnergy -
                   self.atoms.GetPotentialEnergy()) > 1.e-10:
                print unstrainedEnergy, self.atoms.GetPotentialEnergy()
                raise StandardError

        return energy
コード例 #37
0
ファイル: BoxMinimizer.py プロジェクト: auag92/n2dm
    def EnergyFromBoxShape(self, strain):
        if self.atoms == None:
            return

        if self.debug:
            unstrainedEnergy = self.atoms.GetPotentialEnergy()

        unstrainedSCVs = ApplyStrain(self.atoms, strain)

        if self.debug >= 2:
            print "volume:",LA.determinant(self.atoms.GetUnitCell())
    
        energy = self.atoms.GetPotentialEnergy()

        # restore original state
        self.atoms.GetUnitCell().SetBasis(unstrainedSCVs)

        if self.debug:
            if abs(unstrainedEnergy - self.atoms.GetPotentialEnergy()) > 1.e-10:
                print unstrainedEnergy,self.atoms.GetPotentialEnergy()
                raise StandardError

        
        return energy
コード例 #38
0
# Load Data
########################################################################
D = Cook.DummyConvert()
Prods = Cook.DummyConvertSelection()
Prods = Prods[0]
Data1 = D[0]
FC = D[1]
Attr = D[2]
Attrz = copy.deepcopy(Attr)
del Attr[0]
del D

Data1 = Cook.matdevs(Data1)

X = Cook.X(Data1)
Xdash = LinearAlgebra.transpose(X)
B = LinearAlgebra.matmat(Xdash, X)
Data2 = Cook.PreferenceTransformed()

#########################################################################
# Regression Analysis on each respondents data
# Input -> Data1, Data2
# Output -> coefs; contains the coeficients of regression
#########################################################################

Y = []
for i in range(len(Data2)):
    Y.append(Cook.vecdevs(Data2[i]))
leny = len(Y)

Y = LinearAlgebra.transpose(Y)
コード例 #39
0
ファイル: transf.py プロジェクト: serlar/honpas-4.1
cell, atoms = get_info(filename)

print "Old cell:", cell
print toparams(cell)

#
# The transformation matrix is hardwired in this version.
#
matrix = Numeric.array([[ 0., -1., 1.], [ 0., 0., 1.], [ -2., 2. , -1.]])
emat = Numeric.array([[ 0., -1., 1., 0.28488], 
                      [ 0., 0., 1.,0.12343], 
                      [ -2., 2. , -1., 0.0],
                      [ 0.0, 0.0, 0.0, 1.0] ])

invemat = LinearAlgebra.inverse(emat)

# Extend matrix to deal with translations, in the crystallographic way
#
print atoms
natoms = atoms.shape[0]
ones= 1 + Numeric.zeros((natoms,1))
print ones.shape
extatom = Numeric.concatenate((atoms,ones),axis=1)
print extatom

print "---------------"

newcell = Numeric.dot(matrix,cell)
print newcell
print toparams(newcell)
コード例 #40
0
import ranlib
コード例 #41
0
def Predictor_Corrector(Q,
                        c,
                        A,
                        b,
                        tol,
                        kmax=1000,
                        rho=.95,
                        mu0=1e1,
                        mumin=1e-9):
    """
    Run Interior Point Meherotra Predictor Corrector Method to solve
    the quadratic programming problem:
    min (1/2)x^T*Q*x + c^T*x subject to Ax = b and x >= 0,

    That is, it solves
    min (1/2)x^T*Q*x + c^T*x - mu*sum(ln(x_i)) subject to Ax = b
    using a two phase approach:
    1) Find feasible initial condition with Newton Inexact Line Search
    2) Predictor Corrector Method for determining actual optimal

    Input Arguments:
    Q     -- The matrix of coefficients in the quadratic portion of the problem
    c     -- The vector describing the linear function to minimize
    A     -- Matrix of coefficients for linear constraints
    b     -- The Right-hand side vector for the linear constraints
    tol   -- Error tolerance for stopping conditions
             - If a scalar, then used as tolerance for both phases
             - If a tuple, tol[0] is tolerance for Phase I and
               tol[1] is tolerance for Phase II
    kmax  -- Maximum steps allowed, used for stopping condition
             - If a scalar, then used as kmax for both phases
             - If a tuple, kmax[0] is kmax for Phase I and
               kmax[1] is kmax for Phase II
    rho   -- Used for decreasing the strength of the barrier
             - at each iteration mu becomes rho*mu
             - Only used in Phase 1
    mu0   -- Starting value of mu for the step size
             - Only used in Phase 1
    mumin -- Minimum strength of the barrier

    Returns:
    If the optimal is found within tolerance
    x     -- Coordinates of the optimal value
    k     -- Three element array:
             [Total iters, # iters Phase I, # iters Phase II]

    Errors:
    Raises a DimensionMismatchError if the dimensions of the matrices are not compatible

    Warnings:
    Issuse a NonConvergenceError if the optimum cannot be found within tolerance
    """
    # Check if the dimensions of A and b are compatible
    compat, error = _DimensionsCompatible_EqualityOnly(Q, c, A, b)
    if not compat:
        raise DimensionMismatchError(error)

    # Check if tolerance is tuple or scalar
    if not isinstance(tol, tuple):
        tol = (tol, tol)
    if not isinstance(kmax, tuple):
        kmax = (kmax, kmax)

    # For convenience in defining the needed matrices
    m, n = A.shape

    # To track the total number of iterations for both phases
    iters = [0, 0, 0]

    x0 = np.ones((n, 1))
    lamb = np.zeros((m, 1))
    s = np.ones((n, 1))

    # Phase I - find a solution in the feasible region
    # - Can use the Newton's Inexact Line Search for this
    Q_p1 = np.eye(n)
    c_p1 = -1 * np.ones((n, 1))
    x_feas, lamb, s, iters[1] = _Barrier_Worker_EqualityOnly(
        Q_p1, c_p1, A, b, x0, lamb, s, tol[0], kmax[0], rho, mu0, mumin)

    # The above Phase one doesn't take Q or c into account, in particular with regards to lamb and s
    # Here so improve the point from Phase I for s and lamb
    Qxc = np.matmul(Q, x_feas) + c
    s = np.maximum(Qxc, 0) + 1e-4 * np.ones(c.shape)
    lamb = myLA.lowRank_MinNormLS(
        A.T, -np.minimum(Qxc, 0) - 1e-4 * np.ones(c.shape))

    # Phase II
    Q_p2 = Q.copy()
    c_p2 = c.copy()

    x_PD, lamb, s, iters[2] = _PD_Worker(Q_p2, c_p2, A, b, x_feas, lamb, s,
                                         tol[1], kmax[1], mumin)

    iters[0] = iters[1] + iters[2]
    return x_PD, iters
コード例 #42
0
def NERBsIntersect(nerb1,
                   nerb2
                   ):
    '''
    nerb1 - type list, a line defined by a northing, easting, range & bearing
    
    nerb2 - type list, a line defined by a northing, easting, range & bearing

    returns a northing, easting and flag

    flag indicates that the intersection point lies within the range & bearing
    of nerb1

    This function will fail if the two lines are parallel, this must be trapped
    in some future revison
    '''
    theta1 = math.fmod(450-nerb1[3], 360)   # convert bearing to math angle
    theta2 = math.fmod(450-nerb2[3], 360)   # yes, it's the same formula for
                                            #   math to bearing angle
    
##    if theta1 == 90 or theta1 == 270:
##        a1 = 0
##        b1 = -1
##        c1 = nerb1[1]
##    else:
##        a1 = 1
##        b1 = -math.tan(math.radians(theta1))
##        c1 = nerb1[0]-nerb1[1]*math.tan(math.radians(theta1))
##
##    if theta2 == 90 or theta2 == 270:
##        a2 = 0
##        b2 = -1
##        c2 = nerb2[1]
##    else:
##        a2 = 1
##        b2 = -math.tan(math.radians(theta2))
##        c2 = nerb2[0]-nerb2[1]*math.tan(math.radians(theta2))
##
##    a = N.array([(a1,b1),(a2,b2)])
##    b = N.array([(c1),(c2)])
##    try:
##        c = LA.solve_linear_equations(a,b)
##    except LA.LinAlgError:
##        # print'Singular matrix'
##        return (0,0,0)  # return zero's, the flag is zero so the
##                        #   data is ignored anyway
    
    # New Section
    if theta1 == 90 or theta1 == 270:
        c = [nerb2[0]-math.tan(math.radians(theta2))*(nerb2[1]-nerb1[1]), nerb1[1]]
    elif theta2 == 90 or theta2 == 270:
        c = [nerb1[0]-math.tan(math.radians(theta1))*(nerb1[1]-nerb2[1]), nerb2[1]]
    else:
        a1 = 1
        b1 = -math.tan(math.radians(theta1))
        c1 = nerb1[0]-nerb1[1]*math.tan(math.radians(theta1))
        a2 = 1
        b2 = -math.tan(math.radians(theta2))
        c2 = nerb2[0]-nerb2[1]*math.tan(math.radians(theta2))

        a = N.array([(a1,b1),(a2,b2)])
        b = N.array([(c1),(c2)])
        try:
            c = LA.solve_linear_equations(a,b)
        except LA.LinAlgError:
            # print'Singular matrix'
            return (0,0,0)  # return zero's, the flag is zero so the
                            #   data is ignored anyway
    # End of New Section
                    
    temp = GridRangeBearing((0, nerb1[0], nerb1[1], ''),
                            (0, c[0], c[1], '')
                            )
    
    flag=0
    if temp[0] < nerb1[2]:
        if abs(nerb1[3]-temp[1])<15 or abs(abs(nerb1[3]-temp[1])-360)<15:
            flag = 1

    return (c[0], c[1], flag)
コード例 #43
0
    def eigenv_calccomb(self, matrix_hessian, jobid, verbose):
        '''Calculates eigenvectors and eigenvalues of a matrix.'''

        if verbose == True:
            print 'calculating eigenvalues and eigenvectors of the ' + str(
                len(matrix_hessian)) + 'x' + str(
                    len(matrix_hessian)) + ' Hessian matrix'

        import LinearAlgebra
        ## diagonalize hessian matrix
        eigen_tuple = LinearAlgebra.Heigenvectors(matrix_hessian)
        ## parse eigenvalues and eigenvectors
        eigenvalues = list(eigen_tuple[0])
        eigenvectors = list(eigen_tuple[1])
        ## organize eigenvalues and eigenvectors in list
        eigen_list = zip(eigenvalues, eigenvectors)
        ## sort list
        eigen_list.sort()
        ## parse sorted eigenvalues and eigenvectors
        eigenvalues = [
            eigen_list[eigen][0] for eigen in range(len(eigen_list))
        ]
        eigenvectors = [
            eigen_list[eigen][1] for eigen in range(len(eigen_list))
        ]
        if verbose == True:
            lines = ['rows=modes, cols=coordinates\n']
            for mode in range(6, len(eigenvectors)):
                lines += [str(eigenvectors[mode]) + '\n']
            fd = open('%s_eigenvectors.txt' % (jobid), 'w')
            fd.writelines(lines)
            fd.close()

        import math, Numeric

        ## calculate length of mode 7 (equals 1 when using module linearalgebra)
        len7 = math.sqrt(
            sum(
                Numeric.array(eigenvectors[6]) *
                Numeric.array(eigenvectors[6])))

        ##        ## loop over modes
        ##        for i in range(7,len(eigenvalues)-1):
        ##
        ##            ## calculate length of mode i
        ##            leni = math.sqrt(sum(Numeric.array(eigenvectors[i])*Numeric.array(eigenvectors[i])))
        ##
        ##            ## scale length of mode i relative to length of mode 7
        ##            lenfactor = (len7/leni)/(eigenvalues[i]/eigenvalues[6])
        ##            for j in range(len(eigenvectors[i])):
        ##                eigenvectors[i][j] *= lenfactor

        ## copy lists of eigenvectors to eigenvectors_combined
        eigenvectors_combined = []
        for mode in range(len(eigenvalues)):
            eigenvectors_combined.append(list(eigenvectors[mode]))
        ## change mode i to be the sum of modes 7 to i
        for mode in range(7, len(eigenvalues)):
            for coordinate in range(len(eigenvalues)):
                eigenvectors_combined[mode][
                    coordinate] += eigenvectors_combined[mode - 1][coordinate]


##        print 'calculated eigenvalues and eigenvectors of the '+str(len(matrix_hessian))+'x'+str(len(matrix_hessian))+' Hessian matrix'

        return eigenvectors, eigenvalues, eigenvectors_combined
コード例 #44
0
    m[4 * i + 5][4 * i + 2] = 1
    m[4 * i + 5][4 * i + 3] = .5
    m[4 * i + 5][4 * i + 4] = 0
    m[4 * i + 5][4 * i + 5] = 0
    m[4 * i + 5][4 * i + 6] = -1
    m[4 * i + 5][4 * i + 7] = .5

m[n * 4 + 2][2] = 1
m[n * 4 + 3][3] = 1

m[0][n * 4 + 2] = 1
m[1][n * 4 + 3] = 1


def printarr(m):
    for j in range(n * 4 + 4):
        for i in range(n * 4 + 4):
            print '%6.1f' % m[j][i],
        print ''


sys.output_line_width = 160
#print array2string(m, precision = 3)
mi = la.inverse(m)
#printarr(mi)
print ''
for j in range(n + 1):
    for k in range(4):
        print '%7.2f' % mi[j * 4 + k][(n / 2) * 4 + 2],
    print ''
コード例 #45
0
ファイル: newbox.py プロジェクト: pyx-project/pyx
def showcircle(normcurve_pt):
    gx = 350
    gy = 200
    hx = -1
    hy = 2
    cos = hx/math.sqrt(hx*hx+hy*hy)
    sin = hy/math.sqrt(hx*hx+hy*hy)

    r = 16

    dx =                                                             normcurve_pt.x0_pt
    cx =                                       3*normcurve_pt.x1_pt - 3*normcurve_pt.x0_pt
    bx =                   3*normcurve_pt.x2_pt - 6*normcurve_pt.x1_pt + 3*normcurve_pt.x0_pt
    ax = normcurve_pt.x3_pt - 3*normcurve_pt.x2_pt + 3*normcurve_pt.x1_pt -   normcurve_pt.x0_pt

    dy =                                                             normcurve_pt.y0_pt
    cy =                                       3*normcurve_pt.y1_pt - 3*normcurve_pt.y0_pt
    by =                   3*normcurve_pt.y2_pt - 6*normcurve_pt.y1_pt + 3*normcurve_pt.y0_pt
    ay = normcurve_pt.y3_pt - 3*normcurve_pt.y2_pt + 3*normcurve_pt.y1_pt -   normcurve_pt.y0_pt

    def x(t, gx=gx):
        return ax*t*t*t+bx*t*t+cx*t+normcurve_pt.x0_pt
    def y(t, gy=gy):
        return ay*t*t*t+by*t*t+cy*t+normcurve_pt.y0_pt
    def xdot(t):
        return 3*ax*t*t+2*bx*t+cx
    def ydot(t):
        return 3*ay*t*t+2*by*t+cy

    # we need to find roots of the following polynom:
    # (xdot(t)**2+ydot(t)**2)*((x(t)-gx)*hy-(y(t)-gy)*hx)**2-r*r*(xdot(t)*hx+ydot(t)*hy)**2 == 0

    # the polynom is of order 10. its coefficients are:

    coeffs = [9*(ax**2+ay**2)*(hy*ax-ay*hx)**2, # * t**10,

              -6*(hy*ax-ay*hx)*(-5*ax**2*bx*hy+3*ax**2*hx*by-2*ax*by*ay*hy+
              2*ax*hx*bx*ay-3*ay**2*bx*hy+5*hx*ay**2*by), # * t**9, etc.

              -30*hy*hx*ay*ax**2*cx-32*hy*hx*ay*bx**2*ax-42*hy*hx*bx*ax**2*by-18*hy*hx*ax**3*cy+
              24*hy**2*ax**3*cx+37*hy**2*bx**2*ax**2+24*hx**2*ay**3*cy+37*hx**2*by**2*ay**2-
              30*hy*hx*ay**2*ax*cy-32*hy*hx*ay*ax*by**2-42*hy*hx*by*ay**2*bx-18*hy*hx*ay**3*cx+
              6*hy**2*ax**2*cy*ay+4*hy**2*ax**2*by**2+24*hy**2*bx*ax*by*ay+18*hy**2*ay**2*cx*ax+
              9*hy**2*ay**2*bx**2+6*hx**2*ay**2*cx*ax+4*hx**2*ay**2*bx**2+24*hx**2*bx*ax*by*ay+
              18*hx**2*ax**2*cy*ay+9*hx**2*ax**2*by**2,

              20*hx**2*by**3*ay+8*hx**2*by*ay*bx**2+4*hx**2*cx*bx*ay**2-18*hx**2*ax**2*ay*gy+
              18*hx**2*ax**2*ay*dy+20*hy**2*bx**3*ax+18*hy**2*ax**3*dx+12*hx**2*by*ay*cx*ax+18*
              hx**2*cy*by*ax**2+12*hx**2*bx*ax*by**2+8*hy**2*bx*ax*by**2+4*hy**2*cy*by*ax**2-
              18*hy**2*ay**2*ax*gx+18*hy**2*ay**2*ax*dx+18*hy**2*cx*bx*ay**2+12*hy**2*by*ay*bx**2
              +58*hy**2*cx*bx*ax**2-8*hy*hx*ay*bx**3+18*hy*hx*ax**3*gy-18*hy*hx*ax**3*dy-
              18*hy*hx*ay**3*dx-8*hy*hx*ax*by**3+58*hx**2*cy*by*ay**2+24*hx**2*bx*ax*cy*ay+
              12*hy**2*bx*ax*cy*ay+24*hy**2*by*ay*cx*ax-18*hy**2*ax**3*gx-44*hy*hx*ay*cx*bx*ax+
              18*hy*hx*ay*ax**2*gx-18*hy*hx*ay*ax**2*dx-30*hy*hx*by*ax**2*cx-32*hy*hx*by*bx**2*ax-
              42*hy*hx*bx*ax**2*cy+18*hy*hx*ay**3*gx-44*hy*hx*ay*cy*by*ax-30*hy*hx*bx*cy*ay**2-
              32*hy*hx*ay*bx*by**2-42*hy*hx*by*ay**2*cx+18*hy*hx*ay**2*ax*gy-
              18*hy*hx*ay**2*ax*dy-18*hx**2*ay**3*gy+18*hx**2*ay**3*dy,

              hx**2*cx**2*ay**2+46*hy**2*cx*bx**2*ax-42*hy**2*bx*ax**2*gx+42*hy**2*bx*ax**2*dx+
              46*hx**2*cy*by**2*ay-42*hx**2*by*ay**2*gy+42*hx**2*by*ay**2*dy-8*hy*hx*bx*by**3+
              6*hy**2*cy*ay*bx**2+8*hy**2*by**2*cx*ax-18*hy**2*ay**2*bx*gx+18*hy**2*ay**2*bx*dx+
              6*hx**2*by**2*cx*ax+8*hx**2*cy*ay*bx**2-18*hx**2*ax**2*by*gy+18*hx**2*ax**2*by*dy-
              8*hy*hx*by*bx**3+4*hy**2*bx**4+22*hy**2*cx**2*ax**2+22*hx**2*cy**2*ay**2+hy**2*cy**2*ax**2+
              4*hy**2*by**2*bx**2+9*hy**2*cx**2*ay**2+4*hx**2*by**2*bx**2+9*hx**2*cy**2*ax**2+
              4*hx**2*by**4-14*hy*hx*ay*cy**2*ax-44*hy*hx*ay*cy*by*bx-30*hy*hx*cx*cy*ay**2-
              32*hy*hx*ay*cx*by**2+42*hy*hx*by*ay**2*gx-42*hy*hx*by*ay**2*dx-16*hy*hx*cy*by**2*ax+
              24*hy*hx*by*ay*ax*gy-24*hy*hx*by*ay*ax*dy+18*hy*hx*ay**2*bx*gy-18*hy*hx*ay**2*bx*dy+
              8*hy**2*cy*by*bx*ax+12*hy**2*cy*ay*cx*ax-24*hy**2*by*ay*ax*gx+24*hy**2*by*ay*ax*dx+
              24*hy**2*cx*bx*by*ay+8*hx**2*cx*bx*by*ay+12*hx**2*cy*ay*cx*ax-24*hx**2*bx*ax*ay*gy+
              24*hx**2*bx*ax*ay*dy+24*hx**2*cy*by*bx*ax-14*hy*hx*ay*cx**2*ax-16*hy*hx*ay*cx*bx**2+
              24*hy*hx*ay*bx*ax*gx-24*hy*hx*ay*bx*ax*dx-44*hy*hx*by*cx*bx*ax+18*hy*hx*by*ax**2*gx-
              18*hy*hx*by*ax**2*dx-30*hy*hx*cy*ax**2*cx-32*hy*hx*cy*bx**2*ax+42*hy*hx*bx*ax**2*gy-
              42*hy*hx*bx*ax**2*dy,

              12*hx**2*cy*by**3+12*hy**2*cx*bx**3+34*hx**2*cy**2*by*ay-30*hx**2*cy*ay**2*gy+
              30*hx**2*cy*ay**2*dy-32*hx**2*by**2*ay*gy+32*hx**2*by**2*ay*dy+2*hx**2*cx**2*by*ay+
              4*hx**2*cx*bx*by**2-8*hx**2*bx**2*ay*gy+8*hx**2*bx**2*ay*dy+8*hx**2*bx**2*cy*by+
              12*hx**2*cy**2*bx*ax-18*hx**2*ax**2*cy*gy+8*hx**2*cx*bx*cy*ay-12*hx**2*cx*ax*ay*gy+
              12*hx**2*cx*ax*ay*dy+12*hx**2*cx*ax*cy*by-24*hx**2*bx*ax*by*gy+24*hx**2*bx*ax*by*dy+
              18*hx**2*ax**2*cy*dy-8*hy*hx*cy*bx**3-8*hy*hx*cx*by**3+34*hy**2*cx**2*bx*ax-
              30*hy**2*cx*ax**2*gx+30*hy**2*cx*ax**2*dx-32*hy**2*bx**2*ax*gx+32*hy**2*bx**2*ax*dx+
              2*hy**2*cy**2*bx*ax+4*hy**2*bx**2*cy*by-8*hy**2*by**2*ax*gx+8*hy**2*by**2*ax*dx+
              8*hy**2*cx*bx*by**2+12*hy**2*cx**2*by*ay-18*hy**2*ay**2*cx*gx+18*hy**2*ay**2*cx*dx-
              10*hy*hx*ay*cx**2*bx+12*hy*hx*ay*cx*ax*gx-12*hy*hx*ay*cx*ax*dx+
              8*hy*hx*ay*bx**2*gx-8*hy*hx*ay*bx**2*dx-14*hy*hx*by*cx**2*ax-16*hy*hx*by*cx*bx**2+
              24*hy*hx*by*bx*ax*gx-24*hy*hx*by*bx*ax*dx-44*hy*hx*cy*cx*bx*ax+18*hy*hx*cy*ax**2*gx-
              18*hy*hx*cy*ax**2*dx+30*hy*hx*ax**2*cx*gy-30*hy*hx*ax**2*cx*dy+32*hy*hx*bx**2*ax*gy-
              32*hy*hx*bx**2*ax*dy-32*hy*hx*ay*by**2*dx-16*hy*hx*cy*by**2*bx+8*hy*hx*ax*by**2*gy+
              32*hy*hx*ay*by**2*gx-44*hy*hx*ay*cy*by*cx+12*hy*hx*ax*cy*ay*gy-12*hy*hx*ax*cy*ay*dy+
              24*hy*hx*by*ay*bx*gy-24*hy*hx*by*ay*bx*dy+30*hy*hx*cy*ay**2*gx-30*hy*hx*cy*ay**2*dx-
              14*hy*hx*ay*cy**2*bx-10*hy*hx*by*cy**2*ax-8*hy*hx*ax*by**2*dy+18*hy*hx*ay**2*cx*gy-
              18*hy*hx*ay**2*cx*dy+8*hy**2*cx*ax*cy*by-12*hy**2*cy*ay*ax*gx+12*hy**2*cy*ay*ax*dx+
              12*hy**2*cx*bx*cy*ay-24*hy**2*by*ay*bx*gx+24*hy**2*by*ay*bx*dx,

              hy**2*bx**2*cy**2+13*hy**2*cx**2*bx**2+9*hx**2*ax**2*gy**2-9*r**2*ax**2*hx**2-
              9*r**2*ay**2*hy**2+9*hx**2*ax**2*dy**2+hx**2*cx**2*by**2+4*hx**2*bx**2*cy**2+8*hy**2*cx**3*ax+
              8*hx**2*cy**3*ay+13*hx**2*cy**2*by**2-8*hx**2*by**3*gy+8*hx**2*by**3*dy+9*hx**2*ay**2*gy**2+
              9*hx**2*ay**2*dy**2+4*hy**2*cx**2*by**2+9*hy**2*ay**2*gx**2+9*hy**2*ay**2*dx**2-8*hy**2*bx**3*gx+
              8*hy**2*bx**3*dx+9*hy**2*ax**2*gx**2+9*hy**2*ax**2*dx**2-18*hx**2*ay**2*gy*dy+2*hx**2*cx**2*cy*ay+
              6*hx**2*cx*ax*cy**2-8*hx**2*bx**2*by*gy+8*hx**2*bx**2*by*dy-18*hx**2*ax**2*gy*dy+8*hy*hx*by**3*gx-
              8*hy*hx*by**3*dx-2*hy*hx*cy**3*ax+2*hy**2*cx*ax*cy**2+6*hy**2*cx**2*cy*ay-8*hy**2*by**2*bx*gx+
              8*hy**2*by**2*bx*dx-18*hy**2*ay**2*gx*dx-18*hy**2*ax**2*gx*dx-18*r**2*ax*ay*hx*hy-
              44*hx**2*cy*by*ay*gy+44*hx**2*cy*by*ay*dy-8*hx**2*cx*bx*ay*gy+8*hx**2*cx*bx*ay*dy+
              8*hx**2*cx*bx*cy*by-12*hx**2*cx*ax*by*gy+12*hx**2*cx*ax*by*dy-24*hx**2*bx*ax*cy*gy+
              24*hx**2*bx*ax*cy*dy+8*hy*hx*bx*by**2*gy-8*hy*hx*bx*by**2*dy+18*hy*hx*ay**2*dx*gy-
              14*hy*hx*ay*cy**2*cx-18*hy*hx*ay**2*gx*gy-18*hy*hx*ay**2*dx*dy-16*hy*hx*cy*by**2*cx+
              18*hy*hx*ay**2*gx*dy-10*hy*hx*by*cy**2*bx+44*hy*hx*ay*cy*by*gx-44*hy*hx*ay*cy*by*dx+
              8*hy*hx*cy*by*ax*gy-8*hy*hx*cy*by*ax*dy+12*hy*hx*bx*cy*ay*gy-12*hy*hx*bx*cy*ay*dy+
              24*hy*hx*by*ay*cx*gy-24*hy*hx*by*ay*cx*dy-8*hy**2*cy*by*ax*gx+8*hy**2*cy*by*ax*dx+
              8*hy**2*cx*bx*cy*by-12*hy**2*cy*ay*bx*gx+12*hy**2*cy*ay*bx*dx-24*hy**2*by*ay*cx*gx+
              24*hy**2*by*ay*cx*dx-44*hy**2*cx*bx*ax*gx+44*hy**2*cx*bx*ax*dx-2*hy*hx*ay*cx**3+
              8*hy*hx*bx**3*gy-8*hy*hx*bx**3*dy+8*hy*hx*ay*cx*bx*gx-8*hy*hx*ay*cx*bx*dx-
              10*hy*hx*by*cx**2*bx+12*hy*hx*by*cx*ax*gx-12*hy*hx*by*cx*ax*dx+8*hy*hx*by*bx**2*gx-
              8*hy*hx*by*bx**2*dx-14*hy*hx*cy*cx**2*ax-16*hy*hx*cy*cx*bx**2+24*hy*hx*cy*bx*ax*gx-
              24*hy*hx*cy*bx*ax*dx+44*hy*hx*cx*bx*ax*gy-44*hy*hx*cx*bx*ax*dy-18*hy*hx*ax**2*gx*gy+
              18*hy*hx*ax**2*gx*dy+18*hy*hx*ax**2*dx*gy-18*hy*hx*ax**2*dx*dy,

              6*hx**2*cy**3*by-24*hx**2*by*ay*gy*dy-8*hy**2*cy*by*bx*gx-14*hy**2*cx**2*ax*gx-
              12*hy*hx*r**2*bx*ay+2*hy*hx*cx**2*ay*gx-12*r**2*bx*ax*hx**2-12*r**2*by*ay*hy**2+
              16*hy**2*cx*bx**2*dx+6*hy**2*cx**3*bx-16*hy**2*cx*bx**2*gx+14*hy**2*cx**2*ax*dx+
              12*hy**2*bx*ax*gx**2+12*hy**2*bx*ax*dx**2-2*hy*hx*by*cx**3+4*hx**2*cx*bx*cy**2-
              2*hx**2*cx**2*ay*gy+2*hx**2*cx**2*ay*dy+2*hx**2*cx**2*cy*by+12*hx**2*bx*ax*gy**2+
              12*hx**2*bx*ax*dy**2-8*hx**2*cy*bx**2*gy+8*hx**2*cy*bx**2*dy+16*hx**2*cy*by**2*dy-
              14*hx**2*cy**2*ay*gy+14*hx**2*cy**2*ay*dy+12*hx**2*by*ay*gy**2+12*hx**2*by*ay*dy**2+
              4*hy**2*cx**2*cy*by-2*hy**2*cy**2*ax*gx+2*hy**2*cy**2*ax*dx+2*hy**2*cx*bx*cy**2+
              12*hy**2*by*ay*gx**2+12*hy**2*by*ay*dx**2-8*hy**2*cx*by**2*gx+8*hy**2*cx*by**2*dx-
              24*hy**2*bx*ax*gx*dx-2*hy*hx*cx**2*ay*dx+8*hy*hx*by*cx*bx*gx-8*hy*hx*by*cx*bx*dx-
              10*hy*hx*cy*cx**2*bx+12*hy*hx*cy*cx*ax*gx-12*hy*hx*cy*cx*ax*dx+8*hy*hx*cy*bx**2*gx-
              8*hy*hx*cy*bx**2*dx+14*hy*hx*cx**2*ax*gy-14*hy*hx*cx**2*ax*dy+16*hy*hx*cx*bx**2*gy-
              16*hy*hx*cx*bx**2*dy-24*hy*hx*bx*ax*gx*gy+24*hy*hx*bx*ax*gx*dy+24*hy*hx*bx*ax*dx*gy-
              24*hy*hx*bx*ax*dx*dy-2*hy*hx*cy**3*bx+14*hy*hx*cy**2*ay*gx-14*hy*hx*cy**2*ay*dx-
              10*hy*hx*by*cy**2*cx+16*hy*hx*cy*by**2*gx-16*hy*hx*cy*by**2*dx+2*hy*hx*cy**2*ax*gy-
              2*hy*hx*cy**2*ax*dy+8*hy*hx*cy*by*bx*gy-8*hy*hx*cy*by*bx*dy+12*hy*hx*cx*cy*ay*gy-
              12*hy*hx*cx*cy*ay*dy+8*hy*hx*cx*by**2*gy-8*hy*hx*cx*by**2*dy-24*hy*hx*by*ay*gx*gy+
              24*hy*hx*by*ay*gx*dy+24*hy*hx*by*ay*dx*gy-24*hy*hx*by*ay*dx*dy-8*hx**2*cx*bx*by*gy+
              8*hx**2*cx*bx*by*dy-24*hx**2*bx*ax*gy*dy-12*hx**2*cy*cx*ax*gy+12*hx**2*cy*cx*ax*dy-
              16*hx**2*cy*by**2*gy+8*hy**2*cy*by*bx*dx-24*hy**2*by*ay*gx*dx-12*hy**2*cx*cy*ay*gx+
              12*hy**2*cx*cy*ay*dx-12*hy*hx*r**2*ax*by,

              hy**2*cy**2*cx**2-4*r**2*hy**2*by**2+4*hx**2*bx**2*dy**2+4*hx**2*by**2*gy**2-
              4*r**2*hx**2*bx**2+4*hy**2*by**2*dx**2+4*hy**2*by**2*gx**2+4*hx**2*by**2*dy**2+
              hx**2*cy**2*cx**2+4*hy**2*bx**2*dx**2+8*hy**2*cy*by*cx*dx+4*hx**2*bx**2*gy**2+
              2*hy*hx*cy**2*bx*gy+4*hy**2*bx**2*gx**2-2*hy*hx*cy**2*bx*dy-10*hy*hx*cy**2*by*dx-
              8*hy**2*cy*by*cx*gx+10*hy*hx*cy**2*by*gx-6*hy*hx*r**2*cx*ay-10*hx**2*cy**2*by*gy+
              10*hx**2*cy**2*by*dy+6*hx**2*cy*ay*gy**2+6*hx**2*cy*ay*dy**2-8*hx**2*by**2*gy*dy-
              10*hy**2*cx**2*bx*gx+10*hy**2*cx**2*bx*dx+6*hy**2*cx*ax*gx**2+6*hy**2*cx*ax*dx**2-
              8*hy**2*bx**2*gx*dx-6*r**2*hx**2*cx*ax-2*hy**2*cy**2*bx*gx+2*hy**2*cy**2*bx*dx+
              6*hy**2*cy*ay*gx**2+6*hy**2*cy*ay*dx**2-8*hy**2*by**2*gx*dx-2*hy*hx*cy**3*cx-
              6*r**2*hy**2*cy*ay-2*hy*hx*cy*cx**3-2*hx**2*cx**2*by*gy+2*hx**2*cx**2*by*dy+
              6*hx**2*cx*ax*gy**2+6*hx**2*cx*ax*dy**2-8*hx**2*bx**2*gy*dy+hx**2*cy**4+
              hy**2*cx**4-12*hx**2*cy*ay*gy*dy-12*hy**2*cx*ax*gx*dx-8*hy*hx*r**2*bx*by-
              6*hy*hx*r**2*ax*cy-12*hy**2*cy*ay*gx*dx+8*hy*hx*cy*by*cx*gy-8*hy*hx*cy*by*cx*dy-
              12*hy*hx*cy*ay*gx*gy+12*hy*hx*cy*ay*gx*dy+12*hy*hx*cy*ay*dx*gy-
              12*hy*hx*cy*ay*dx*dy-8*hy*hx*by**2*gx*gy+8*hy*hx*by**2*gx*dy+8*hy*hx*by**2*dx*gy-
              8*hy*hx*by**2*dx*dy+2*hy*hx*cx**2*by*gx-2*hy*hx*cx**2*by*dx+8*hy*hx*cy*cx*bx*gx-
              8*hy*hx*cy*cx*bx*dx+10*hy*hx*cx**2*bx*gy-10*hy*hx*cx**2*bx*dy-12*hy*hx*cx*ax*gx*gy+
              12*hy*hx*cx*ax*gx*dy+12*hy*hx*cx*ax*dx*gy-12*hy*hx*cx*ax*dx*dy-8*hy*hx*bx**2*gx*gy+
              8*hy*hx*bx**2*gx*dy+8*hy*hx*bx**2*dx*gy-8*hy*hx*bx**2*dx*dy-8*hx**2*cx*bx*cy*gy+
              8*hx**2*cx*bx*cy*dy-12*hx**2*cx*ax*gy*dy,

              -2*hx**2*cy**3*gy-2*hy**2*cx**3*gx+2*hy**2*cx**3*dx-4*hy*hx*r**2*cx*by+
              2*hy*hx*cy*cx**2*gx+2*hx**2*cy**3*dy-4*r**2*cx*bx*hx**2-4*r**2*cy*by*hy**2-
              2*hy**2*cy**2*cx*gx+2*hy**2*cy**2*cx*dx+4*hy**2*cy*by*gx**2+4*hy**2*cy*by*dx**2+
              4*hx**2*cy*by*gy**2+4*hx**2*cy*by*dy**2+2*hy*hx*cx**3*gy-2*hy*hx*cx**3*dy+
              4*hy**2*cx*bx*gx**2+4*hy**2*cx*bx*dx**2-2*hx**2*cy*cx**2*gy+2*hx**2*cy*cx**2*dy+
              4*hx**2*cx*bx*gy**2+4*hx**2*cx*bx*dy**2+2*hy*hx*cy**3*gx-2*hy*hx*cy**3*dx-
              8*hy**2*cy*by*gx*dx-4*hy*hx*r**2*bx*cy-8*hx**2*cy*by*gy*dy-2*hy*hx*cy*cx**2*dx-
              8*hy*hx*cx*bx*gx*gy+8*hy*hx*cx*bx*gx*dy+8*hy*hx*cx*bx*dx*gy-
              8*hy*hx*cx*bx*dx*dy-8*hy**2*cx*bx*gx*dx-8*hx**2*cx*bx*gy*dy+2*hy*hx*cy**2*cx*gy-
              2*hy*hx*cy**2*cx*dy-8*hy*hx*cy*by*gx*gy+8*hy*hx*cy*by*gx*dy+
              8*hy*hx*cy*by*dx*gy-8*hy*hx*cy*by*dx*dy,

              cx**2*hy**2*gx**2-2*cx**2*hy**2*gx*dx+cx**2*hy**2*dx**2-2*r**2*hx*hy*cx*cy+
              cy**2*hx**2*gy**2-2*cy**2*hx**2*gy*dy+cy**2*hx**2*dy**2+cy**2*hy**2*gx**2-
              2*cy**2*hy**2*gx*dx+cy**2*hy**2*dx**2-2*cy**2*hx*hy*gy*gx+2*cy**2*hx*hy*dy*gx+
              2*cy**2*hx*hy*gy*dx-2*cy**2*hx*hy*dy*dx+cx**2*hx**2*gy**2-2*cx**2*hx**2*gy*dy+
              cx**2*hx**2*dy**2-r**2*hy**2*cy**2-2*cx**2*hx*hy*gy*gx+2*cx**2*hx*hy*dy*gx+
              2*cx**2*hx*hy*gy*dx-2*cx**2*hx*hy*dy*dx-r**2*hx**2*cx**2]

    # def z(t):
    #     res = 0
    #     for x in coeffs:
    #         res = res*t + x
    #     return res

    # def zdot(t):
    #     res = 0
    #     i = len(coeffs)
    #     for x in coeffs[:-1]:
    #         res = res*t + (i-1)*x
    #         i -= 1
    #     return res

    # def newton(t):
    #     # newton iteration to find the zero of z with t being the starting value for t
    #     if t < 0: t = 0
    #     if t > 1: t = 1
    #     slow = 1
    #     try:
    #         isz=z(t)
    #     except (ValueError, ArithmeticError):
    #         return
    #     loop = 0
    #     while abs(isz) > 1e-6:
    #         try:
    #             nt = t - slow * isz/zdot(t)
    #             newisz = z(nt)
    #         except (ValueError, ArithmeticError):
    #             slow *= 0.5 # we might have slow down the newton iteration
    #         else:
    #             t = nt
    #             isz = newisz
    #             if slow <= 0.5:
    #                 slow *= 2
    #         if loop > 100:
    #             break
    #         loop += 1
    #     else:
    #         return t

    # def ts():
    #     epsilon = 1e-5
    #     res = []
    #     count = 100
    #     for x in range(count+1):
    #        t = newton(x/float(count))
    #        if t is not None and 0-0.5*epsilon < t < 1+0.5*epsilon:
    #            res.append(t)
    #     res.sort()
    #     i = 1
    #     while len(res) > i:
    #         if res[i] > res[i-1] + epsilon:
    #             i += 1
    #         else:
    #             del res[i]
    #     return res

    # use Numeric to find the roots (via an equivalent eigenvalue problem)
    import Numeric, LinearAlgebra
    mat = Numeric.zeros((10, 10), Numeric.Float)
    for i in range(9):
        mat[i+1][i] = 1
    for i in range(10):
        mat[0][i] = -coeffs[i+1]/coeffs[0]
    ists = [zero.real for zero in LinearAlgebra.eigenvalues(mat) if -1e-10 < zero.imag < 1e-10 and 0 <= zero.real <= 1]

    for t in ists:
        isl = (xdot(t)*(x(t)-gx)+ydot(t)*(y(t)-gy))/(xdot(t)*cos+ydot(t)*sin)
        c.fill(path.circle_pt(x(t), y(t), 1), [color.rgb.green])
        c.stroke(path.circle_pt(gx+isl*cos, gy+isl*sin, r), [color.rgb.green])
コード例 #46
0
def exercise_eigensystem():
    m = [
        0.13589302585705959, -0.041652833629281995, 0.0, -0.02777294381303139,
        0.0, -0.028246956907939123, -0.037913518508910102,
        -0.028246956907939123, 0.028246956907939127, 0.066160475416849232, 0.0,
        -1.998692119493731e-18, 0.0, 1.9342749002960583e-17,
        2.1341441122454314e-17, -0.041652833629281995, 0.16651402880692701,
        -0.041652833629282252, -0.054064923492613354, -0.041657741914063608,
        -0.027943612435735281, 0.058527480224229975, -0.027943612435735132,
        -0.034820867346713427, -0.030583867788494697, 0.062764479782448576,
        1.2238306785281e-33, 0.0, 2.0081205093967302e-33,
        8.4334666705394195e-34, 0.0, -0.041652833629282252,
        0.13589302585705959, 0.0, -0.041574928784987308, -0.028246956907939064,
        0.0, -0.028246956907939064, 0.063090910812553094, 0.028246956907939068,
        -0.034843953904614026, -1.9986921194937106e-18,
        -8.9229029691439759e-18, 1.0316952905846454e-17,
        3.3927420561961863e-18, -0.02777294381303139, -0.05406492349261334,
        0.0, 1.0754189352289423, 0.0, 0.055233150062734049,
        -0.030424256077943676, 0.02480889398479039, -0.024808893984790394,
        -0.024808893984790425, 0.0, -6.8972719971392908e-18,
        -1.7405118013554239e-17, 6.1312902919038241e-18,
        -4.3765557245111121e-18, 0.0, -0.041657741914063601,
        -0.041574928784987308, 0.0, 1.0754189352289425, 0.02824584556921347,
        0.0, 0.056206884746120872, -0.028245845569213546, -0.02824584556921347,
        -0.027961039176907447, 5.9506047506615062e-18, 0.0,
        -1.4122576510436466e-18, -7.3628624017051534e-18,
        -0.028246956907939123, -0.027943612435735277, -0.028246956907939064,
        0.055233150062734056, 0.028245845569213474, 0.058637637326162888,
        -0.021712364921140592, 0.038218912676148069, -0.039777184406252442,
        -0.036925272405022302, 0.0015582717301043682, 4.0451470549537404e-18,
        0.0, -1.3724767734658202e-17, -1.7769914789611943e-17,
        -0.037913518508910102, 0.058527480224229982, 0.0,
        -0.030424256077943652, 0.0, -0.021712364921140592, 0.28175206518101342,
        0.0039066487534216467, -0.0039066487534216484, -0.26003970025987289,
        0.0, 7.5625035918149771e-18, 1.2380916665439571e-17,
        -1.0148697613996034e-16, -9.6668563066335756e-17,
        -0.028246956907939123, -0.027943612435735128, -0.028246956907939064,
        0.02480889398479039, 0.056206884746120879, 0.038218912676148069,
        0.0039066487534216484, 0.058637637326162798, -0.031992570455625299,
        -0.042125561429569719, -0.026645066870537512, 4.0451470549537242e-18,
        9.6341055014789307e-18, -2.0511818948105707e-17,
        -1.4922860501580496e-17, 0.028246956907939127, -0.034820867346713427,
        0.063090910812553094, -0.024808893984790394, -0.028245845569213508,
        -0.039777184406252442, -0.0039066487534216501, -0.031992570455625306,
        0.2922682186182603, 0.043683833159674099, -0.26027564816263499,
        -5.2586006938540899e-18, 0.0, 9.7867664544895616e-18,
        1.5045367148343648e-17, 0.066160475416849232, -0.030583867788494701,
        0.028246956907939068, -0.024808893984790466, -0.028245845569213474,
        -0.036925272405022302, -0.26003970025987289, -0.042125561429569719,
        0.043683833159674092, 0.29696497266489519, -0.0015582717301043699,
        -7.5250966340669269e-19, 2.6213138712286628e-17,
        -1.5094268920622606e-17, 1.1871379455070714e-17, 0.0,
        0.062764479782448576, -0.034843953904614026, 0.0,
        -0.027961039176907457, 0.0015582717301043665, 0.0,
        -0.026645066870537509, -0.26027564816263499, -0.0015582717301043699,
        0.28692071503317257, -3.8759778199373453e-18, 3.9691789817943108e-17,
        -8.14982209920807e-18, 3.5417945538672385e-17, -1.998692119493731e-18,
        1.6308338425568088e-33, -1.9986921194937102e-18,
        -6.8972719971392892e-18, 5.950604750661507e-18, 4.0451470549537412e-18,
        7.5625035918149756e-18, 4.0451470549537242e-18,
        -5.2586006938540899e-18, -7.5250966340669346e-19,
        -3.8759778199373446e-18, 0.054471159454508082, 0.0064409353489570716,
        0.0035601061597435495, -0.044470117945807464, 0.0, 0.0,
        -8.9229029691439759e-18, -1.7405118013554239e-17, 0.0, 0.0,
        1.2380916665439569e-17, 9.6341055014789307e-18, 0.0,
        2.6213138712286628e-17, 3.9691789817943114e-17, 0.0064409353489570777,
        0.47194161564298681, -0.17456675614101194, 0.29093392415301783,
        1.9342749002960583e-17, 1.4951347746978839e-33, 1.0316952905846454e-17,
        6.1312902919038033e-18, -1.4122576510436468e-18,
        -1.3724767734658202e-17, -1.0148697613996034e-16,
        -2.0511818948105704e-17, 9.7867664544895616e-18,
        -1.5094268920622603e-17, -8.1498220992080684e-18,
        0.0035601061597435478, -0.17456675614101194, 0.61470061296798617,
        0.4365737506672307, 2.1341441122454314e-17, 1.5911491532730484e-34,
        3.392742056196186e-18, -4.3765557245111453e-18,
        -7.3628624017051534e-18, -1.7769914789611943e-17,
        -9.6668563066335731e-17, -1.4922860501580496e-17,
        1.5045367148343648e-17, 1.1871379455070717e-17, 3.5417945538672392e-17,
        -0.044470117945807464, 0.29093392415301783, 0.4365737506672307,
        0.77197779276605605
    ]
    #
    m = flex.double(m)
    m.resize(flex.grid(15, 15))
    s = tntbx.eigensystem.real(m)
    e_values = s.values()
    #
    if (Numeric is not None):
        n = Numeric.asarray(m)
        n.shape = (15, 15)
        n_values = LinearAlgebra.eigenvalues(n)
        assert len(e_values) == len(n_values)
        #
        print '               Eigenvalues'
        print '      %-16s %-16s' % ('TNT', 'Numpy')
        for i, e, n in zip(count(1), e_values, n_values):
            if (isinstance(e, complex)): e = e.real
            if (isinstance(n, complex)): n = n.real
            print "  %2d %16.12f %16.12f" % (i, e, n)
    #
    sorted_values = e_values.select(
        flex.sort_permutation(data=e_values, reverse=True))
    assert approx_equal(sorted_values, [
        1.1594490522786849, 1.0940938851317932, 1.0788186474215089,
        0.68233800454109983, 0.62042869735706307, 0.53297576878337871,
        0.18708677344352156, 0.16675360561093594, 0.12774949816038345,
        0.071304124011754358, 0.02865105770313877, 0.027761263516876356,
        1.5830173657858035e-17, 2.6934929627275647e-18, -5.5511151231257827e-17
    ])
コード例 #47
0
ファイル: CARSMath.py プロジェクト: cowanml/epicsPython
def polyfitw(x, y, w, ndegree, return_fit=0):
   """
   Performs a weighted least-squares polynomial fit with optional error estimates.

   Inputs:
      x: 
         The independent variable vector.

      y: 
         The dependent variable vector.  This vector should be the same 
         length as X.

      w: 
         The vector of weights.  This vector should be same length as 
         X and Y.

      ndegree: 
         The degree of polynomial to fit.

   Outputs:
      If return_fit==0 (the default) then polyfitw returns only C, a vector of 
      coefficients of length ndegree+1.
      If return_fit!=0 then polyfitw returns a tuple (c, yfit, yband, sigma, a)
         yfit:  
            The vector of calculated Y's.  Has an error of + or - Yband.

         yband: 
            Error estimate for each point = 1 sigma.

         sigma: 
            The standard deviation in Y units.

         a: 
            Correlation matrix of the coefficients.

   Written by:   George Lawrence, LASP, University of Colorado,
                 December, 1981 in IDL.
                 Weights added, April, 1987,  G. Lawrence
                 Fixed bug with checking number of params, November, 1998, 
                 Mark Rivers.  
                 Python version, May 2002, Mark Rivers
   """
   n = min(len(x), len(y)) # size = smaller of x,y
   m = ndegree + 1         # number of elements in coeff vector
   a = Numeric.zeros((m,m),Numeric.Float)  # least square matrix, weighted matrix
   b = Numeric.zeros(m,Numeric.Float)    # will contain sum w*y*x^j
   z = Numeric.ones(n,Numeric.Float)     # basis vector for constant term

   a[0,0] = Numeric.sum(w)
   b[0] = Numeric.sum(w*y)

   for p in range(1, 2*ndegree+1):     # power loop
      z = z*x   # z is now x^p
      if (p < m):  b[p] = Numeric.sum(w*y*z)   # b is sum w*y*x^j
      sum = Numeric.sum(w*z)
      for j in range(max(0,(p-ndegree)), min(ndegree,p)+1):
         a[j,p-j] = sum

   a = LinearAlgebra.inverse(a)
   c = Numeric.matrixmultiply(b, a)
   if (return_fit == 0):
      return c     # exit if only fit coefficients are wanted

   # compute optional output parameters.
   yfit = Numeric.zeros(n,Numeric.Float)+c[0]   # one-sigma error estimates, init
   for k in range(1, ndegree +1):
      yfit = yfit + c[k]*(x**k)  # sum basis vectors
   var = Numeric.sum((yfit-y)**2 )/(n-m)  # variance estimate, unbiased
   sigma = Numeric.sqrt(var)
   yband = Numeric.zeros(n,Numeric.Float) + a[0,0]
   z = Numeric.ones(n,Numeric.Float)
   for p in range(1,2*ndegree+1):     # compute correlated error estimates on y
      z = z*x		# z is now x^p
      sum = 0.
      for j in range(max(0, (p - ndegree)), min(ndegree, p)+1):
         sum = sum + a[j,p-j]
      yband = yband + sum * z      # add in all the error sources
   yband = yband*var
   yband = Numeric.sqrt(yband)
   return c, yfit, yband, sigma, a
コード例 #48
0
ファイル: polymat.py プロジェクト: pexip/os-fonts-roboto
def solve(path):
    if path[0][2] == '{': closed = 0
    else: closed = 1
    dxs = []
    dys = []
    chords = []
    for i in range(len(path) - 1):
        dxs.append(path[i + 1][0] - path[i][0])
        dys.append(path[i + 1][1] - path[i][1])
        chords.append(hypot(dxs[-1], dys[-1]))
    nominal_th = []
    nominal_k = []
    if not closed:
        nominal_th.append(atan2(dys[0], dxs[0]))
        nominal_k.append(0)
    for i in range(1 - closed, len(path) - 1 + closed):
        x0, y0, t0 = path[(i + len(path) - 1) % len(path)]
        x1, y1, t1 = path[i]
        x2, y2, t2 = path[(i + 1) % len(path)]
        dx = float(x2 - x0)
        dy = float(y2 - y0)
        ir2 = dx * dx + dy * dy
        x = ((x1 - x0) * dx + (y1 - y0) * dy) / ir2
        y = ((y1 - y0) * dx - (x1 - x0) * dy) / ir2
        th = fit_arc(x, y) + atan2(dy, dx)
        bend_angle = mod_2pi(atan2(y2 - y1, x2 - x1) - atan2(y1 - y0, x1 - x0))
        k = 2 * bend_angle / (hypot(y2 - y1, x2 - x1) +
                              hypot(y1 - y0, x1 - x0))
        print '% bend angle', bend_angle, 'k', k
        if t1 == ']':
            th = atan2(y1 - y0, x1 - x0)
            k = 0
        elif t1 == '[':
            th = atan2(y2 - y1, x2 - x1)
            k = 0
        nominal_th.append(th)
        nominal_k.append(k)
    if not closed:
        nominal_th.append(atan2(dys[-1], dxs[-1]))
        nominal_k.append(0)
    print '%', nominal_th
    print '0 0 1 setrgbcolor .5 setlinewidth'
    plot_path(path, nominal_th, nominal_k)
    plot_ks(path, nominal_th, nominal_k)
    th = nominal_th[:]
    k = nominal_k[:]
    n = 8
    for i in range(n):
        ev = make_error_vec(path, th, k)
        m = make_matrix(path, th, k)
        #print m
        #print 'inverse:'
        #print la.inverse(m)
        v = dot(la.inverse(m), ev)
        #print v
        for j in range(len(path)):
            th[j] += 1. * v[2 * j]
            k[j] -= 1. * .5 * v[2 * j + 1]
        if i == n - 1:
            print '0 0 0 setrgbcolor 1 setlinewidth'
        elif i == 0:
            print '1 0 0 setrgbcolor'
        elif i == 1:
            print '0 0.5 0 setrgbcolor'
        elif i == 2:
            print '0.3 0.3 0.3 setrgbcolor'
        plot_path(path, th, k)
        plot_ks(path, th, k)
    print '% th:', th
    print '% k:', k
コード例 #49
0
 def inverse(self):
     "Returns the inverse."
     import LinearAlgebra
     inverse = LinearAlgebra.inverse(self.asMatrix())
     return Quaternion(inverse[:, 0])
コード例 #50
0
                                row_sub] = value  #upper super off-diagonal; yixj, zixj, ziyj
                            matrix_hessian[
                                3 * col_sup + row_sub, 3 * row_sup +
                                col_sub] = value  #lower super off-diagonal; xjyi, xjzi, yjzi
                            matrix_hessian[
                                3 * row_sup + col_sub, 3 * row_sup +
                                row_sub] -= value  ##super diagonal; yixi, zixi, ziyi
                            matrix_hessian[
                                3 * col_sup + row_sub, 3 * col_sup +
                                col_sub] -= value  ##super diagonal; yjxj, zjxj, zjyj

##
## calculate eigenvectors
##
## diagonalize hessian matrix
eigen_tuple = LinearAlgebra.Heigenvectors(matrix_hessian)
## parse eigenvalues and eigenvectors
eigenvalues = list(eigen_tuple[0])
eigenvectors = list(eigen_tuple[1])
## organize eigenvalues and eigenvectors in list
eigen_list = zip(eigenvalues, eigenvectors)
## sort list
eigen_list.sort()
## parse sorted eigenvalues and eigenvectors
eigenvalues = [eigen_list[eigen][0] for eigen in range(len(eigen_list))]
eigenvectors = [eigen_list[eigen][1] for eigen in range(len(eigen_list))]

print eigenvalues
for i in range(6, 9):
    print eigenvectors[i]
print matrix_hessian
コード例 #51
0
ファイル: MLab.py プロジェクト: KarolNi/VROOM-
def svd(v):
    """[u,x,v] = svd(m) return the singular value decomposition of m.
    """
    return LinearAlgebra.singular_value_decomposition(v)
コード例 #52
0
ファイル: Lsf.py プロジェクト: juselius/arcs
def lsf(data, a, n):
    xmat = setxmat(data, a, n)
    yvec = setyvec(data, n)
    return LinearAlgebra.linear_least_squares(xmat, yvec)
コード例 #53
0
ca_avg = Numeric.average(ca)
ca2 = ca - ca_avg[Numeric.NewAxis, :]
ca_cov = Numeric.zeros((num_coor, num_coor), Numeric.Float)
for ts in ca2:
    ca_cov += Numeric.outerproduct(ts, ts)
ca_cov /= num_ts
ca_cov1 = Numeric.matrixmultiply(ca_cov, mass_matrix)
del ca_cov
ca_cov2 = Numeric.matrixmultiply(mass_matrix, ca_cov1)
del ca_cov1

N_av = 6.0221367e23
hplanck_bar = 6.6260755e-34 / (2 * Numeric.pi)
k = 1.3806580000000001e-23
T = 300  # kelvin
eigenv, eigenvec = LinearAlgebra.eigenvectors(ca_cov2)
real = [e.real / 100. for e in eigenv]
f = open('eigenval.dat', 'w')
for i, val in enumerate(real):
    f.write("%i\t%s\n" % (i + 1, val))
f.close()

eigenval = eigenv * 1.6605402e-27 * 1e-20
omega_i = Numeric.sqrt(k * T / (eigenval))

term = (hplanck_bar * omega_i) / (k * T)
summation_terms = (term /
                   (Numeric.exp(term) - 1.)) - Numeric.log(1. -
                                                           Numeric.exp(-term))
S_ho = k * N_av * Numeric.sum(summation_terms)
コード例 #54
0
def getGraph():
    stockName = request.args.get('s')
    var = stockName
    old_stdout = sys.stdout
    sys.stdout = open(os.devnull, "w")
    if var != 'null':  # ONLY PRECEDE IF WE HAVE A COMPANY

        Coefficients = numpy.zeros((11, 1))

        timeBegin = 2010

        totalDataCurrent = Fetching.fetchDataToday(
            var, timeBegin
        )  # This gets all the data from the start year to 3 days ago (give or take a work day)

        googData = Fetching.fetchGoogData(
            var)  # Fetch Todays data from google finance

        Prediction_Data = Fetching.fetchDataSpec(
            var, (datetime.now() + timedelta(days=-45))
        )  # Get the data from just the past month for the prediciton part

        Prediction_Data_Length = len(
            Prediction_Data.Close
        )  # Lenght of the predictin Data to save the recalc of it

        Coefficients = LinearAlgebra.coeffcients_Generator(
            LinearAlgebra.makeXVals_Matrix(10, timeBegin,
                                           Prediction_Data_Length),
            LinearAlgebra.makeY_Matrix(Prediction_Data.Low)
        )  #coeffcients for prediction fucntion a0-a10

        Prediction_Model = LinearAlgebra.makeOutY(
            Coefficients, Prediction_Data_Length, timeBegin,
            totalDataCurrent.High, googData
        )  # Gets Prediciton Model or scatter of predicted points these points are also normalized

        pointY = LinearAlgebra.getPointY(
            Coefficients, timeBegin, googData[0]['LastTradePrice'],
            totalDataCurrent.High[len(totalDataCurrent) - 1]
        )  #gets Predictiion Point for the next day independently so I can calculate individual days

        R = RSI.PredictRSI(totalDataCurrent.Close)

        pointY = LinearAlgebra.getPointY(
            Coefficients, timeBegin, googData[0]['LastTradePrice'],
            totalDataCurrent.Low[len(totalDataCurrent) - 1]
        )  #gets Predictiion Point for the next day independently so I can calculate individual days

        url = Graphing.totalTogether(
            var, totalDataCurrent, googData, Prediction_Model, pointY,
            R)  #Print Final Graph with everything together

        url = url + ".embed?width=640&height=480"
        ret = "<iframe width='640' height='480' frameborder='0' scrolling='no' src='" + url + "'> </iframe>"
        sys.stdout.close()
        sys.stdout = old_stdout
        return ret
    else:
        sys.stdout.close()
        sys.stdout = old_stdout
        return "false"
コード例 #55
0
    w_matrix_list.append(w_matrix_row)
dbg_file.write('\nW Matrix List\n')
dbg_file.write(str(w_matrix_list))
w_matrix = Numeric.array(w_matrix_list)
dbg_file.write('\nW Matrix\n')
dbg_file.write(str(w_matrix))
q_list = []
#for q in offset_table.values():
#   q_list.append(list(q))
for k in keys_in_order:
    q_list.append(list(k))
dbg_file.write('\nQ List\n')
dbg_file.write(str(q_list))
q_vector = Numeric.array(q_list)
print 'Solving for alpha vector...'
alpha_vector = LinearAlgebra.solve_linear_equations(w_matrix, q_vector)
dbg_file.write('\nAlpha Vector\n')
dbg_file.write(str(alpha_vector))
print 'Alpha Vector found.'
out_file = ''
if argc == '2':
    out_file = sys.argv[1]
else:
    out_file = sys.argv[2]
in_file.close()
out_file = file(out_file, 'w')
alpha_vector_list = alpha_vector.tolist()
dbg_file.write('\nCheck Solution\n')
solution_check = Numeric.matrixmultiply(w_matrix, alpha_vector)
dbg_file.write(str(solution_check))
コード例 #56
0
ファイル: Trajectory.py プロジェクト: fxia22/ASM_xf
    def __init__(self, trajectory, object, first=0, last=None, skip=1,
                 reference = None):
        self.trajectory = trajectory
        universe = trajectory.universe
        if last is None: last = len(trajectory)
        first_conf = trajectory.configuration[first]
        offset = universe.contiguousObjectOffset([object], first_conf, 1)
        if reference is None:
            reference = first_conf
        reference = universe.contiguousObjectConfiguration([object],
                                                           reference)
        steps = (last-first+skip-1)/skip
        mass = object.mass()
        ref_cms = object.centerOfMass(reference)
        atoms = object.atomList()

        possq = Numeric.zeros((steps,), Numeric.Float)
        cross = Numeric.zeros((steps, 3, 3), Numeric.Float)
        rcms = Numeric.zeros((steps, 3), Numeric.Float)

        # cms of the CONTIGUOUS object made of CONTINUOUS atom trajectories 
        for a in atoms:
            r = trajectory.readParticleTrajectory(a, first, last, skip,
                                                  "box_coordinates").array
            w = a._mass/mass
            Numeric.add(rcms, w*r, rcms)
            if offset is not None:
                Numeric.add(rcms, w*offset[a].array, rcms)
        
        # relative coords of the CONTIGUOUS reference
        r_ref = Numeric.zeros((len(atoms), 3), Numeric.Float)
        for a in range(len(atoms)):
            r_ref[a] = atoms[a].position(reference).array - ref_cms.array

        # main loop: storing data needed to fill M matrix 
        for a in range(len(atoms)):
            r = trajectory.readParticleTrajectory(atoms[a],
                                                  first, last, skip,
                                                  "box_coordinates").array
            r = r - rcms # (a-b)**2 != a**2 - b**2
            if offset is not None:
                Numeric.add(r, offset[atoms[a]].array,r)
            trajectory._boxTransformation(r, r)
            w = atoms[a]._mass/mass
            Numeric.add(possq, w*Numeric.add.reduce(r*r, -1), possq)
            Numeric.add(possq, w*Numeric.add.reduce(r_ref[a]*r_ref[a],-1),
                        possq)
            Numeric.add(cross, w*r[:,:,Numeric.NewAxis]*r_ref[Numeric.NewAxis,
                                                              a,:],cross)
        self.trajectory._boxTransformation(rcms, rcms)

        # filling matrix M (formula no 40)
        k = Numeric.zeros((steps, 4, 4), Numeric.Float)
        k[:, 0, 0] = -cross[:, 0, 0]-cross[:, 1, 1]-cross[:, 2, 2]
        k[:, 0, 1] = cross[:, 1, 2]-cross[:, 2, 1]
        k[:, 0, 2] = cross[:, 2, 0]-cross[:, 0, 2]
        k[:, 0, 3] = cross[:, 0, 1]-cross[:, 1, 0]
        k[:, 1, 1] = -cross[:, 0, 0]+cross[:, 1, 1]+cross[:, 2, 2]
        k[:, 1, 2] = -cross[:, 0, 1]-cross[:, 1, 0]
        k[:, 1, 3] = -cross[:, 0, 2]-cross[:, 2, 0]
        k[:, 2, 2] = cross[:, 0, 0]-cross[:, 1, 1]+cross[:, 2, 2]
        k[:, 2, 3] = -cross[:, 1, 2]-cross[:, 2, 1]
        k[:, 3, 3] = cross[:, 0, 0]+cross[:, 1, 1]-cross[:, 2, 2]
        del cross
        for i in range(1, 4):
            for j in range(i):
                k[:, i, j] = k[:, j, i]
        Numeric.multiply(k, 2., k)
        for i in range(4):
            Numeric.add(k[:,i,i], possq, k[:,i,i])
        del possq

        quaternions = Numeric.zeros((steps, 4), Numeric.Float)
        fit = Numeric.zeros((steps,), Numeric.Float)
	import LinearAlgebra
        for i in range(steps):
            e, v = LinearAlgebra.eigenvectors(k[i])
            j = Numeric.argmin(e)
            if e[j] < 0.:
                fit[i] = 0.
            else:
                fit[i] = Numeric.sqrt(e[j])
            if v[j,0] < 0.: quaternions[i] = -v[j] # eliminate jumps
            else: quaternions[i] = v[j]
        self.fit = fit
        self.cms = rcms
        self.quaternions = quaternions
コード例 #57
0
def polyfitw(x, y, w, ndegree, return_fit=0):
    """
   Performs a weighted least-squares polynomial fit with optional error estimates.

   Inputs:
      x: 
         The independent variable vector.

      y: 
         The dependent variable vector.  This vector should be the same 
         length as X.

      w: 
         The vector of weights.  This vector should be same length as 
         X and Y.

      ndegree: 
         The degree of polynomial to fit.

   Outputs:
      If return_fit==0 (the default) then polyfitw returns only C, a vector of 
      coefficients of length ndegree+1.
      If return_fit!=0 then polyfitw returns a tuple (c, yfit, yband, sigma, a)
         yfit:  
            The vector of calculated Y's.  Has an error of + or - Yband.

         yband: 
            Error estimate for each point = 1 sigma.

         sigma: 
            The standard deviation in Y units.

         a: 
            Correlation matrix of the coefficients.

   Written by:   George Lawrence, LASP, University of Colorado,
                 December, 1981 in IDL.
                 Weights added, April, 1987,  G. Lawrence
                 Fixed bug with checking number of params, November, 1998, 
                 Mark Rivers.  
                 Python version, May 2002, Mark Rivers
   """
    n = min(len(x), len(y))  # size = smaller of x,y
    m = ndegree + 1  # number of elements in coeff vector
    a = Numeric.zeros((m, m),
                      Numeric.Float)  # least square matrix, weighted matrix
    b = Numeric.zeros(m, Numeric.Float)  # will contain sum w*y*x^j
    z = Numeric.ones(n, Numeric.Float)  # basis vector for constant term

    a[0, 0] = Numeric.sum(w)
    b[0] = Numeric.sum(w * y)

    for p in range(1, 2 * ndegree + 1):  # power loop
        z = z * x  # z is now x^p
        if (p < m): b[p] = Numeric.sum(w * y * z)  # b is sum w*y*x^j
        sum = Numeric.sum(w * z)
        for j in range(max(0, (p - ndegree)), min(ndegree, p) + 1):
            a[j, p - j] = sum

    a = LinearAlgebra.inverse(a)
    c = Numeric.matrixmultiply(b, a)
    if (return_fit == 0):
        return c  # exit if only fit coefficients are wanted

    # compute optional output parameters.
    yfit = Numeric.zeros(
        n, Numeric.Float) + c[0]  # one-sigma error estimates, init
    for k in range(1, ndegree + 1):
        yfit = yfit + c[k] * (x**k)  # sum basis vectors
    var = Numeric.sum((yfit - y)**2) / (n - m)  # variance estimate, unbiased
    sigma = Numeric.sqrt(var)
    yband = Numeric.zeros(n, Numeric.Float) + a[0, 0]
    z = Numeric.ones(n, Numeric.Float)
    for p in range(1,
                   2 * ndegree + 1):  # compute correlated error estimates on y
        z = z * x  # z is now x^p
        sum = 0.
        for j in range(max(0, (p - ndegree)), min(ndegree, p) + 1):
            sum = sum + a[j, p - j]
        yband = yband + sum * z  # add in all the error sources
    yband = yband * var
    yband = Numeric.sqrt(yband)
    return c, yfit, yband, sigma, a
コード例 #58
0
ファイル: polymat-bad.py プロジェクト: 420peacemaker/roboto
    m[4 * i + 5][4 * i + 0] = 0
    m[4 * i + 5][4 * i + 1] = 0
    m[4 * i + 5][4 * i + 2] = 1
    m[4 * i + 5][4 * i + 3] = .5
    m[4 * i + 5][4 * i + 4] = 0
    m[4 * i + 5][4 * i + 5] = 0
    m[4 * i + 5][4 * i + 6] = -1
    m[4 * i + 5][4 * i + 7] = .5

m[n * 4 + 2][2] = 1
m[n * 4 + 3][3] = 1

m[0][n * 4 + 2] = 1
m[1][n * 4 + 3] = 1

def printarr(m):
    for j in range(n * 4 + 4):
        for i in range(n * 4 + 4):
            print '%6.1f' % m[j][i],
        print ''

sys.output_line_width = 160
#print array2string(m, precision = 3)
mi = la.inverse(m)
#printarr(mi)
print ''
for j in range(n + 1):
    for k in range(4):
        print '%7.2f' % mi[j * 4 + k][(n / 2) * 4 + 2],
    print ''
コード例 #59
0
ファイル: MLab.py プロジェクト: KarolNi/VROOM-
def eig(v):
    """[x,v] = eig(m) returns the eigenvalues of m in x and the corresponding
    eigenvectors in the rows of v.
    """
    return LinearAlgebra.eigenvectors(v)