예제 #1
0
    def updatedata(self, A):
        # Update b, c
        try:
            ALU = linalg.lu_factor(A)
            BC = linalg.lu_solve(ALU, c_[linalg.lu_solve(ALU, self.data.b + 1e-8*self.data.Brand[:,:1]), \
                                 self.data.c + 1e-8*self.data.Crand[:,:1]], trans=1)
            C = linalg.lu_solve(ALU, BC[:,-1:])
            B = BC[:,:1]
        except:
            if self.C.verbosity >= 1:
                print 'Warning: Problem updating border vectors.  Using svd...'
            U, S, Vh = linalg.svd(A)
            B = U[:,-1:]
            C = transpose(Vh)[:,-1:]

        bmult = cmult = 1
        if matrixmultiply(transpose(self.data.b), B) < 0:
            bmult = -1
        if matrixmultiply(transpose(self.data.c), C) < 0:
            cmult = -1
        self.data.b = bmult*B*(linalg.norm(A,1)/linalg.norm(B))
        self.data.c = cmult*C*(linalg.norm(A,Inf)/linalg.norm(C))

        # Update
        if self.update:
            self.data.B[:,0] = self.data.b*(linalg.norm(A,1)/linalg.norm(self.data.b))
            self.data.C[:,0] = self.data.c*(linalg.norm(A,Inf)/linalg.norm(self.data.c))

            self.data.B[:,1] = self.data.w[:,2]*(linalg.norm(A,1)/linalg.norm(self.data.w,1))
            self.data.C[:,1] = self.data.v[:,2]*(linalg.norm(A,Inf)/linalg.norm(self.data.v,1))

            self.data.D[0,1] = self.data.g[0,1]
            self.data.D[1,0] = self.data.g[1,0]
예제 #2
0
def intersect_line_ellipsoid(p1, p2, ec, radius_vectors):
    """Determine intersection points between line defined by p1 and p2,
    and ellipsoid defined by centre ec and three radius vectors (tuple
    of tuples, each inner tuple is a radius vector).

    This requires numpy.
    """


    # create transformation matrix that has the radius_vectors
    # as its columns (hence the transpose)
    rv = numpy.transpose(numpy.matrix(radius_vectors))
    # calculate its inverse
    rv_inv = numpy.linalg.pinv(rv)
    
    # now transform the two points
    # all points have to be relative to ellipsoid centre
    # the [0] at the end and the numpy.array at the start is to make sure
    # we pass a row vector (array) to the line_sphere_intersection
    p1_e = numpy.array(numpy.matrixmultiply(rv_inv, numpy.array(p1) - numpy.array(ec)))[0]
    p2_e = numpy.array(numpy.matrixmultiply(rv_inv, numpy.array(p2) - numpy.array(ec)))[0]

    # now we only have to determine the intersection between the points
    # (now transformed to ellipsoid space) with the unit sphere centred at 0
    isects_e = intersect_line_sphere(p1_e, p2_e, (0.0,0.0,0.0), 1.0)

    # transform intersections back to "normal" space
    isects = []
    for i in isects_e:
        # numpy.array(...)[0] is for returning only row of matrix as array
        itemp = numpy.array(numpy.matrixmultiply(rv, numpy.array(i)))[0]
        isects.append(itemp + numpy.array(ec))

    return isects
    def glr_Uellipse(self, position, U, prob):
        """Renders the ellipsoid enclosing the given fractional probability
        given the gaussian variance-covariance matrix U at the given position.
        C=1.8724 = 68%
        """
        ## rotate U
        R  = self.matrix[:3,:3]
        Ur = numpy.matrixmultiply(numpy.matrixmultiply(R, U), numpy.transpose(R))

        Umax = max(linalg.eigenvalues(Ur))
        try:
            limit_radius = Gaussian.GAUSS3C[prob] * MARGIN * math.sqrt(Umax)
        except ValueError:
            limit_radius = 2.0

        try:
            Q = linalg.inverse(Ur)
        except linalg.LinAlgError:
            return
        
        self.object_list.append(
            (14,
             matrixmultiply43(self.matrix, position),
             limit_radius,
             self.material_color_r,
             self.material_color_g,
             self.material_color_b,
             Q,
             -Gaussian.GAUSS3C[prob]**2))
예제 #4
0
    def func(self, X, V):
        k = self.C.TFdata.k
        v1 = self.C.TFdata.v1
        w1 = self.C.TFdata.w1

        if k >=0:
            J_coords = self.F.sysfunc.J_coords
            w = sqrt(k)

            q = v1 - (1j/w)*matrixmultiply(self.F.sysfunc.J_coords,v1)
            p = w1 + (1j/w)*matrixmultiply(transpose(self.F.sysfunc.J_coords),w1)

            p /= linalg.norm(p)
            q /= linalg.norm(q)

            p = reshape(p,(p.shape[0],))
            q = reshape(q,(q.shape[0],))

            direc = conjugate(1/matrixmultiply(transpose(conjugate(p)),q))
            p = direc*p

            l1 = firstlyapunov(X, self.F.sysfunc, w, J_coords=J_coords, p=p, q=q)

            return array([l1])
        else:
            return array([1])
예제 #5
0
    def process(self, X, V, C):
        BifPoint.process(self, X, V, C)

        J_coords = C.CorrFunc.sysfunc.jac(X, C.coords)
        B = C.CorrFunc.sysfunc.hess(X, C.coords, C.coords)

        W, VL, VR = linalg.eig(J_coords, left=1, right=1)

        q = C.CorrFunc.testfunc.data.C / linalg.norm(
            C.CorrFunc.testfunc.data.C)
        p = C.CorrFunc.testfunc.data.B / matrixmultiply(
            transpose(C.CorrFunc.testfunc.data.B), q)

        self.found[-1].eigs = W

        a = 0.5*matrixmultiply(transpose(p), reshape([bilinearform(B[i,:,:], q, q) \
                for i in range(B.shape[0])],(B.shape[0],1)))[0][0]
        if C.verbosity >= 2:
            print('\nChecking...')
            print('  |a| = %f' % a)
            print('\n')

        self.info(C, -1)

        return True
예제 #6
0
def bCorrNumeric(X, Y, DX, beat_input, cut=0.001, app=0, path="./"):
    R = np.transpose(beat_input.sensitivity_matrix)
    b = beat_input.computevectorEXP(X, Y, DX) - beat_input.zerovector
    corr = beat_input.varslist
    m, n = np.shape(R)
    if len(b) == m and len(corr) == n:
        rms, ptop = calcRMSNumeric(b)
        inva = generalized_inverse(R, cut)
        print "initial {RMS, Peak}: { %e , %e } mm" % (rms, ptop)
        print "finding best over", n, "correctors"
        for i in range(n):
            dStren = matrixmultiply(inva[i, :], b)
            bvec = b - matrixmultiply(R[:, i], dStren)
            rm, ptp = calcRMSNumeric(bvec)
            if rm < rms:
                rms = rm
                rbest = i
                rStren = dStren
            if ptp < ptop:
                ptop = ptp
                pbest = i
                pStren = dStren
        print "final {RMS, Peak}: { %e , %e }" % (rms, ptop)
        if rbest == pbest:
            print "best corr:", corr[rbest], '%e' % (rStren), "1/m"
        else:
            print "--- warning: best corr for rms & peak are not same"
            print "RMS best corr:", corr[rbest], '%e' % (rStren), "1/m"
            print "Peak best corr:", corr[pbest], '%e' % (pStren), "1/m"
    else:
        print "dimensional mismatch in input variables"
예제 #7
0
    def updatedata(self, A):
        if self.update:
            if self.corr:
                B = self.data.w
                C = self.data.v
            else:
                # Note: Problem when singular vectors switch smallest singular value (See NewLorenz).
                #       To overcome this, I have implemented a 1e-8 random nudge.
                try:
                    ALU = linalg.lu_factor(A)
                    # BC = linalg.lu_solve(ALU, c_[linalg.lu_solve(ALU, self.data.B), self.data.C], trans=1)
                    # USE OF RANDOM NUDGE
                    BC = linalg.lu_solve(ALU, c_[linalg.lu_solve(ALU, self.data.B + 1e-8*self.data.Brand), \
                                                 self.data.C + 1e-8*self.data.Crand], trans=1)
                    C = linalg.lu_solve(ALU, BC[:,-1*self.data.q:])
                    B = BC[:,0:self.data.p]
                except:
                    if self.C.verbosity >= 1:
                        print('Warning: Problem updating border vectors.  Using svd...')
                    U, S, Vh = linalg.svd(A)
                    B = U[:,-1*self.data.p:]
                    C = transpose(Vh)[:,-1*self.data.q:]

            bmult = cmult = 1
            if matrixmultiply(transpose(self.data.B), B) < 0:
                bmult = -1
            if matrixmultiply(transpose(self.data.C), C) < 0:
                cmult = -1
            self.data.B = bmult*B*(linalg.norm(A,1)/linalg.norm(B))
            self.data.C = cmult*C*(linalg.norm(A,Inf)/linalg.norm(C))
예제 #8
0
def bCorrNumeric(X, Y, DX, beat_input, cut=0.001, app=0, path="./"):
    R = np.transpose(beat_input.sensitivity_matrix)
    b = beat_input.computevectorEXP(X, Y, DX) - beat_input.zerovector
    corr = beat_input.varslist
    m, n = np.shape(R)
    if len(b) == m and len(corr) == n:
        rms, ptop = calcRMSNumeric(b)
        inva = generalized_inverse(R, cut)
        print "initial {RMS, Peak}: { %e , %e } mm" % (rms, ptop)
        print "finding best over", n, "correctors"
        for i in range(n):
            dStren = matrixmultiply(inva[i, :], b)
            bvec = b - matrixmultiply(R[:, i], dStren)
            rm, ptp = calcRMSNumeric(bvec)
            if rm < rms:
                rms = rm
                rbest = i
                rStren = dStren
            if ptp < ptop:
                ptop = ptp
                pbest = i
                pStren = dStren
        print "final {RMS, Peak}: { %e , %e }" % (rms, ptop)
        if rbest == pbest:
            print "best corr:", corr[rbest], '%e' % (rStren), "1/m"
        else:
            print "--- warning: best corr for rms & peak are not same"
            print "RMS best corr:", corr[rbest], '%e' % (rStren), "1/m"
            print "Peak best corr:", corr[pbest], '%e' % (pStren), "1/m"
    else:
        print "dimensional mismatch in input variables"
예제 #9
0
def itrSVD(X,
           Y,
           DX,
           beat_input,
           cut=0.001,
           num_iter=1,
           app=0,
           tol=1e-9,
           path="./"):
    R = np.transpose(beat_input.sensitivity_matrix)
    b = beat_input.computevectorEXP(X, Y, DX) - beat_input.zerovector
    corr = beat_input.varslist
    inva = generalized_inverse(R, cut)
    rmss, ptopp = calcRMSNumeric(b)
    RHO2 = {}
    dStren = np.zeros(len(corr))
    print 'Initial Phase-Beat:', '{RMS,PK2PK}', rmss, ptopp
    for ITER in range(num_iter):  # @UnusedVariable
        dStren = dStren + matrixmultiply(inva, b)
        bvec = b - matrixmultiply(R, dStren)
        rm, ptp = calcRMSNumeric(bvec)
        print 'ITER', num_iter, '{RMS,PK2PK}', rm, ptp
    for j in range(len(corr)):
        RHO2[corr[j]] = dStren[j]
    wrtpar(corr, RHO2, app, path)
예제 #10
0
    def __pade_approximation(self, nodeName, L, M, debug=0):
        assert L == M - 1
        num_moments = L+M+1
        if debug: "DATA L=%s M=%s num_moments=%s" % (L, M, num_moments)

        if debug: print "num_moments", num_moments
        #scaling = 766423.0
        node_index = self.TranslateNode(nodeName)
        node_moments = []
        # step 1: calculate the Moments
        g_inverse = numpy.linalg.inverse(self.G)
        if debug: print "g_inverse", g_inverse
        last_moment = numpy.matrixmultiply(g_inverse, self.B)
        if debug: print "last_moment", last_moment, node_index
        node_moments.append(last_moment[node_index-1][0])

		# test commit
        for i in range(num_moments-1):
            intermediate = -1 * numpy.matrixmultiply(g_inverse, self.C)
            last_moment = numpy.matrixmultiply( intermediate, last_moment )
            moment = self.Scaling * last_moment[node_index-1][0]
            node_moments.append(moment)
            last_moment = self.Scaling * last_moment
            if debug: print "last_moment", last_moment

        print "suggested scaling =", node_moments[0]/node_moments[1]
        if debug: print "node_moments=", node_moments

        # Call the general pade algorithm
        a_coef, b_coef = MathHelpers.my_pade(node_moments, complex=False)

        # Return results
        return a_coef, b_coef, node_moments
예제 #11
0
    def func(self, X, V):
        H = self.F.sysfunc.hess(X, self.F.coords, self.F.coords)
        q = self.F.testfunc.data.v/linalg.norm(self.F.testfunc.data.v)
        p = self.F.testfunc.data.w/matrixmultiply(transpose(self.F.testfunc.data.w),q)

        return array(0.5*matrixmultiply(transpose(p), reshape([bilinearform(H[i,:,:], q, q) \
             for i in range(H.shape[0])],(H.shape[0],1)))[0])
예제 #12
0
    def process(self, X, V, C):
        BifPoint.process(self, X, V, C)

        # Finds the new branch
        J_coords = C.CorrFunc.jac(X, C.coords)
        J_params = C.CorrFunc.jac(X, C.params)
        A = r_[c_[J_coords, J_params], [V]]
        W, VR = linalg.eig(A)
        W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5]
        V1 = real(VR[:,W0[0]])

        H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params)
        c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])])
        c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])])
        c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])])

        beta = 1
        alpha = -1*c22/(2*c12)
        V1 = alpha*V + beta*V1
        V1 /= linalg.norm(V1)

        self.found[-1].eigs = W
        self.found[-1].branch = todict(C, V1)

        self.info(C, -1)

        return True
    def glr_Uaxes(self, position, U, prob, color, line_width):
        """Draw the anisotropic axies of the atom at the given probability.
        """
        ## rotate U
        R  = self.matrix[:3,:3]
        Ur = numpy.matrixmultiply(numpy.matrixmultiply(R, U), numpy.transpose(R))

        evals, evecs = linalg.eigenvectors(Ur)
예제 #14
0
 def calc_orth_symop(self, symop):
     """Calculates the orthogonal space symmetry operation (return SymOp)
     given a fractional space symmetry operation (argument SymOp).
     """
     RF  = numpy.matrixmultiply(symop.R, self.orth_to_frac)
     ORF = numpy.matrixmultiply(self.frac_to_orth, RF)
     Ot  = numpy.matrixmultiply(self.frac_to_orth, symop.t)
     return SpaceGroups.SymOp(ORF, Ot)
예제 #15
0
def pluecker_from_verts(A, B):
    if len(A) == 3:
        A = A[0], A[1], A[2], 1.0
    if len(B) == 3:
        B = B[0], B[1], B[2], 1.0
    A = nx.reshape(A, (4, 1))
    B = nx.reshape(B, (4, 1))
    L = nx.matrixmultiply(A, nx.transpose(B)) - nx.matrixmultiply(
        B, nx.transpose(A))
    return Lmatrix2Lcoords(L)
예제 #16
0
    def process(self, X, V, C):
        BifPoint.process(self, X, V, C)

        # Finds the new branch
        J_coords = C.CorrFunc.jac(X, C.coords)
        J_params = C.CorrFunc.jac(X, C.params)

        singular = True
        perpvec = r_[1, zeros(C.dim - 1)]
        d = 1
        while singular and d <= C.dim:
            try:
                v0 = linalg.solve(r_[c_[J_coords, J_params],
                                  [perpvec]], \
                                  r_[zeros(C.dim-1),1])
            except:
                perpvec = r_[0., perpvec[0:(C.dim - 1)]]
                d += 1
            else:
                singular = False

        if singular:
            raise PyDSTool_ExistError(
                "Problem in _compute: Failed to compute tangent vector.")
        v0 /= linalg.norm(v0)
        V = sign([x for x in v0 if abs(x) > 1e-8][0]) * v0

        A = r_[c_[J_coords, J_params], [V]]
        W, VR = linalg.eig(A)
        W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5]
        V1 = real(VR[:, W0[0]])

        H = C.CorrFunc.hess(X, C.coords + C.params, C.coords + C.params)
        c11 = matrixmultiply(
            self.data.psi,
            [bilinearform(H[i, :, :], V, V) for i in range(H.shape[0])])
        c12 = matrixmultiply(
            self.data.psi,
            [bilinearform(H[i, :, :], V, V1) for i in range(H.shape[0])])
        c22 = matrixmultiply(
            self.data.psi,
            [bilinearform(H[i, :, :], V1, V1) for i in range(H.shape[0])])

        beta = 1
        alpha = -1 * c22 / (2 * c12)
        V1 = alpha * V + beta * V1
        V1 /= linalg.norm(V1)

        self.found[-1].eigs = W
        self.found[-1].branch = todict(C, V1)

        self.info(C, -1)

        return True
예제 #17
0
    def __locate_newton(self, X, C):
        """x[0:self.dim] = (x,alpha)
           x[self.dim] = beta
           x[self.dim+1:2*self.dim] = p
        """
        J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords)
        J_params = C.CorrFunc.jac(X[0:C.dim], C.params)

        return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \
                  matrixmultiply(transpose(J_coords),X[C.dim+1:]), \
                  matrixmultiply(transpose(X[C.dim+1:]),J_params), \
                  matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1]
예제 #18
0
파일: BifPoint.py 프로젝트: mdlama/pydstool
    def __locate_newton(self, X, C):
        """x[0:self.dim] = (x,alpha)
           x[self.dim] = beta
           x[self.dim+1:2*self.dim] = p
        """
        J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords)
        J_params = C.CorrFunc.jac(X[0:C.dim], C.params)

        return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \
                  matrixmultiply(transpose(J_coords),X[C.dim+1:]), \
                  matrixmultiply(transpose(X[C.dim+1:]),J_params), \
                  matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1]
예제 #19
0
파일: misc.py 프로젝트: tclose/pydstool
def firstlyapunov(X,
                  F,
                  w,
                  J_coords=None,
                  V=None,
                  W=None,
                  p=None,
                  q=None,
                  check=False):
    if J_coords is None:
        J_coords = F.jac(X, F.coords)

    if p is None:
        alpha = bilinearform(transpose(J_coords),V[:,0],V[:,1]) - \
                1j*w*matrixmultiply(V[:,0],V[:,1])
        beta = -1*bilinearform(transpose(J_coords),V[:,0],V[:,0]) + \
                1j*w*matrixmultiply(V[:,0],V[:,0])
        q = alpha * V[:, 0] + beta * V[:, 1]

        alpha = bilinearform(J_coords,W[:,0],W[:,1]) + \
                1j*w*matrixmultiply(W[:,0],W[:,1])
        beta = -1*bilinearform(J_coords,W[:,0],W[:,0]) - \
                1j*w*matrixmultiply(W[:,0],W[:,0])
        p = alpha * W[:, 0] + beta * W[:, 1]

        p /= linalg.norm(p)
        q /= linalg.norm(q)

        direc = conjugate(1 / matrixmultiply(conjugate(p), q))
        p = direc * p

    if check:
        print('Checking...')
        print('  |q| = %f' % linalg.norm(q))
        temp = matrixmultiply(conjugate(p), q)
        print('  |<p,q> - 1| = ', abs(temp - 1))
        print('  |Aq - iwq| = %f' %
              linalg.norm(matrixmultiply(J_coords, q) - 1j * w * q))
        print('  |A*p + iwp| = %f\n' %
              linalg.norm(matrixmultiply(transpose(J_coords), p) + 1j * w * p))

    # Compute first lyapunov coefficient
    B = F.hess(X, F.coords, F.coords)
    D = hess3(F, X, F.coords)
    b1 = array([bilinearform(B[i, :, :], q, q) for i in range(B.shape[0])])
    b2 = array([bilinearform(B[i,:,:], conjugate(q),
                          linalg.solve(2*1j*w*eye(F.m) - J_coords, b1)) \
                 for i in range(B.shape[0])])
    b3 = array([bilinearform(B[i,:,:], q, conjugate(q)) \
                 for i in range(B.shape[0])])
    b4 = array([bilinearform(B[i,:,:], q, linalg.solve(J_coords, b3)) \
                 for i in range(B.shape[0])])
    temp = array([trilinearform(D[i,:,:,:],q,q,conjugate(q)) \
                 for i in range(D.shape[0])]) + b2 - 2*b4

    l1 = 0.5 * real(matrixmultiply(conjugate(p), temp))

    return l1
예제 #20
0
    def func(self, X, V):
        F = self.C.CorrFunc
        # print F.testfunc[0]
        # print F.testfunc[0].data
        F.testfunc[0](X,V)
        # print F.testfunc[0].data
        H = F.sysfunc.hess(X, self.F.coords, self.F.coords)
        q = F.testfunc[0].data.v/linalg.norm(F.testfunc[0].data.v)
        p = F.testfunc[0].data.w/matrixmultiply(transpose(F.testfunc[0].data.w),q)

        return array(0.5*matrixmultiply(transpose(p), reshape([bilinearform(H[i,:,:], q, q) \
             for i in range(H.shape[0])],(H.shape[0],1)))[0])
예제 #21
0
    def Cmatrix(self):
        '''
         Calculate the C matrix
        '''
        self.C = []
        self.gamma = []
        self.f1001 = []
        self.f1010 = []
        S = getattr(self, "S")
        R11 = getattr(self, "R11")
        R12 = getattr(self, "R12")
        R21 = getattr(self, "R21")
        R22 = getattr(self, "R22")
        BETX = getattr(self, "BETX")
        BETY = getattr(self, "BETY")
        ALFX = getattr(self, "ALFX")
        ALFY = getattr(self, "ALFY")

        J = numpy.reshape(numpy.array([0, 1, -1, 0]), (2, 2))
        for j in range(0, len(S)):
            R = numpy.array([[R11[j], R12[j]], [R21[j], R22[j]]])

            C = matrixmultiply(-J, matrixmultiply(numpy.transpose(R), J))
            C = (1 / numpy.sqrt(1 + determinant(R))) * C

            g11 = 1 / numpy.sqrt(BETX[j])
            g12 = 0
            g21 = ALFX[j] / numpy.sqrt(BETX[j])
            g22 = numpy.sqrt(BETX[j])
            Ga = numpy.reshape(numpy.array([g11, g12, g21, g22]), (2, 2))

            g11 = 1 / numpy.sqrt(BETY[j])
            g12 = 0
            g21 = ALFY[j] / numpy.sqrt(BETY[j])
            g22 = numpy.sqrt(BETY[j])
            Gb = numpy.reshape(numpy.array([g11, g12, g21, g22]), (2, 2))
            C = matrixmultiply(Ga, matrixmultiply(C, inverse(Gb)))
            gamma = 1 - determinant(C)
            self.gamma.append(gamma)
            C = numpy.ravel(C)
            self.C.append(C)
            self.f1001.append(((C[0] + C[3]) * 1j + (C[1] - C[2])) / 4 / gamma)
            self.f1010.append(
                ((C[0] - C[3]) * 1j + (-C[1] - C[2])) / 4 / gamma)

        self.F1001R = numpy.array(self.f1001).real
        self.F1001I = numpy.array(self.f1001).imag
        self.F1010R = numpy.array(self.f1010).real
        self.F1010I = numpy.array(self.f1010).imag
        self.F1001W = numpy.sqrt(self.F1001R**2 + self.F1001I**2)
        self.F1010W = numpy.sqrt(self.F1010R**2 + self.F1010I**2)
        self.GAMMAC = numpy.array(self.gamma)
예제 #22
0
def bNCorrNumeric(X,
                  Y,
                  DX,
                  beat_input,
                  cut=0.001,
                  ncorr=3,
                  app=0,
                  tol=1e-9,
                  path="./",
                  beta_x=None,
                  beta_y=None):
    R = np.transpose(beat_input.sensitivity_matrix)
    n = np.shape(R)[1]
    b = beat_input.computevectorEXP(X, Y, DX, beta_x,
                                    beta_y) - beat_input.zerovector
    corr = beat_input.varslist
    inva = generalized_inverse(R, cut)
    RHO2 = {}
    rmss, ptopp = calcRMSNumeric(b)
    print 'Initial Phase-beat {RMS,PK2PK}:', rmss, ptopp
    for ITER in range(ncorr):
        for j in range(n):
            if j not in RHO2:
                RHO = [k for k in RHO2.keys()]
                RHO.append(j)
                RR = np.take(R, RHO, 1)
                invaa = np.take(inva, RHO, 0)
                dStren = matrixmultiply(invaa, b)
                #--- calculate residual due to 1..nth corrector
                bvec = b - matrixmultiply(RR, dStren)
                rm, ptp = calcRMSNumeric(bvec)
                if rm < rmss:
                    rmss = rm
                    ptopp = ptp
                    rbest = j
                    rStren = dStren
        print 'ITER:', ITER + 1, '  RMS,PK2PK:', rmss, ptopp
        RHO2[rbest] = (rmss, ptopp)
        if (rm < tol):
            print "RMS converged with", ITER, "correctors"
            break
        if (rm < rmss):
            print "stopped after", ITER, "correctors"
            break
    itr = 0
    RHO3 = {}  #-- make dict RHO3={corr:strength,...}
    for j in RHO2:
        RHO3[corr[j]] = rStren[itr]
        itr += 1
    print '\n', sortDict(RHO3)
    wrtpar(corr, RHO3, app, path)
    return RHO3
예제 #23
0
    def do_svd_clean(self, plane):
        """Does a SVD clean on the given plane"""
        time_start = time.time()
        print "(plane {0}) removing noise floor with SVD".format(plane)

        A = numpy.array(self.sddsfile.dictionary_plane_to_bpms[plane].bpm_data)
        number_of_bpms = A.shape[0]

        if number_of_bpms <= 10:
            sys.exit("Number of bpms <= 10")

        # normalise the matrix
        sqrt_number_of_turns = numpy.sqrt(A.shape[1])
        A_mean = numpy.mean(A)
        A = (A - A_mean) / sqrt_number_of_turns

        if PRINT_TIMES:
            print ">> Time for svdClean (before SVD call): {0}s".format(time.time() - time_start)
        USV = self.get_singular_value_decomposition(A)
        if PRINT_TIMES:
            print ">> Time for svdClean (after SVD call): {0}s".format(time.time() - time_start)

        # remove bad BPM by SVD -tbach
        good_bpm_indices = self.remove_bad_bpms_and_get_good_bpm_indices(USV, plane)
        USV = (USV[0][good_bpm_indices], USV[1], USV[2])
        number_of_bpms = len(good_bpm_indices)
        print ">> Values in GOOD BPMs: "
        print number_of_bpms

        # ----SVD cut for noise floor
        if _InputData.singular_values_amount_to_keep < number_of_bpms:
            print "(plane {0}) amount of singular values to keep: {1}".format(
                plane, _InputData.singular_values_amount_to_keep
            )
            USV[1][_InputData.singular_values_amount_to_keep :] = 0
        else:
            print "requested more singular values than available(={0})".format(number_of_bpms)

        A = matrixmultiply(USV[0], matrixmultiply(numpy.diag(USV[1]), USV[2]))
        # A0 * (A1 * A2) should require less operations than (A0 * A1) * A2,
        #  because of the different sizes
        # A0 has (M, K), A1 has (K, K) and A2 has (K, N) with K=min(M,N)
        # Most of the time, the number of turns is greater then
        #  the number of BPM, so M > N
        # --tbach
        A = (A * sqrt_number_of_turns) + A_mean
        bpmres = numpy.mean(numpy.std(A - self.sddsfile.dictionary_plane_to_bpms[plane].bpm_data, axis=1))
        print "(plane {0}) Average BPM resolution: ".format(plane) + str(bpmres)
        self.sddsfile.dictionary_plane_to_bpms[plane].bpm_data = A
        if PRINT_TIMES:
            print ">> Time for do_svd_clean: {0}s".format(time.time() - time_start)
예제 #24
0
def test_module():
    import random
    import AtomMath
    import FileIO
    import Structure

    R = AtomMath.rmatrixu(numpy.array((0.0, 0.0, 1.0), float), math.pi / 2.0)

    struct1 = FileIO.LoadStructure(fil="/home/jpaint/8rxn/8rxn.pdb")
    struct2 = FileIO.LoadStructure(fil="/home/jpaint/8rxn/8rxn.pdb")

    chn1 = struct1.get_chain("A")
    chn2 = struct2.get_chain("A")

    rc = lambda: 0.1 * (random.random() - 1.0)
    for atm in chn2.iter_atoms():
        atm.position = numpy.matrixmultiply(R, atm.position) + numpy.array(
            (rc(), rc(), rc()), float)

    alist = []

    for atm1 in chn1.iter_atoms():
        if atm1.name != "CA":
            continue

        atm2 = chn2.get_equivalent_atom(atm1)
        if atm2 == None: continue

        alist.append((atm1, atm2))

    sup = SuperimposeAtoms(alist)

    R = sup.R
    Q = sup.Q
    print Q
    print R

    so = sup.src_origin
    do = sup.dst_origin

    sup1 = Structure.Structure(structure_id="JMP1")
    for atm in chn1.iter_atoms():
        atm.position = numpy.matrixmultiply(R, atm.position - so)
        sup1.add_atom(atm)
    FileIO.SaveStructure(fil="super1.pdb", struct=sup1)

    sup2 = Structure.Structure(structure_id="JMP2")
    for atm in chn2.iter_atoms():
        atm.position = atm.position - do
        sup2.add_atom(atm)
    FileIO.SaveStructure(fil="super2.pdb", struct=sup2)
예제 #25
0
def stdForm(a, b):
    def invert(L):  # inverts lower triangular matrix L
        n = len(L)
        for j in range(n - 1):
            L[j, j] = 1.0 / L[j, j]
            for i in range(j + 1, n):
                L[i, j] = -dot(L[i, j:i], L[j:i, j]) / L[i, i]
        L[n - 1, n - 1] = 1.0 / L[n - 1, n - 1]

    n = len(a)
    L = choleski(b)  # COMEBACKTO!!!
    invert(L)
    h = matrixmultiply(b, matrixmultiply(a, transpose(L)))
    return h, transpose(L)
    def Cmatrix(self):
        '''
         Calculate the C matrix
        '''
        self.C = []
        self.gamma = []
        self.f1001 = []
        self.f1010 = []
        S = getattr(self, "S")
        R11 = getattr(self, "R11")
        R12 = getattr(self, "R12")
        R21 = getattr(self, "R21")
        R22 = getattr(self, "R22")
        BETX = getattr(self, "BETX")
        BETY = getattr(self, "BETY")
        ALFX = getattr(self, "ALFX")
        ALFY = getattr(self, "ALFY")

        J = numpy.reshape(numpy.array([0, 1, -1, 0]), (2, 2))
        for j in range(0, len(S)):
            R = numpy.array([[R11[j], R12[j]], [R21[j], R22[j]]])
            
            C = matrixmultiply(-J, matrixmultiply(numpy.transpose(R), J))
            C = (1 / numpy.sqrt(1 + determinant(R))) * C

            g11 = 1 / numpy.sqrt(BETX[j])
            g12 = 0
            g21 = ALFX[j] / numpy.sqrt(BETX[j])
            g22 = numpy.sqrt(BETX[j])
            Ga = numpy.reshape(numpy.array([g11, g12, g21, g22]), (2, 2))

            g11 = 1 / numpy.sqrt(BETY[j])
            g12 = 0
            g21 = ALFY[j] / numpy.sqrt(BETY[j])
            g22 = numpy.sqrt(BETY[j])
            Gb = numpy.reshape(numpy.array([g11, g12, g21, g22]), (2, 2))
            C = matrixmultiply(Ga, matrixmultiply(C, inverse(Gb)))
            gamma = 1 - determinant(C)
            self.gamma.append(gamma)
            C = numpy.ravel(C)
            self.C.append(C)
            self.f1001.append(((C[0] + C[3]) * 1j + (C[1] - C[2])) / 4 / gamma)
            self.f1010.append(((C[0] - C[3]) * 1j + (-C[1] - C[2])) / 4 / gamma)

        self.F1001R = numpy.array(self.f1001).real
        self.F1001I = numpy.array(self.f1001).imag
        self.F1010R = numpy.array(self.f1010).real
        self.F1010I = numpy.array(self.f1010).imag
        self.F1001W = numpy.sqrt(self.F1001R ** 2 + self.F1001I ** 2)
        self.F1010W = numpy.sqrt(self.F1010R ** 2 + self.F1010I ** 2)
예제 #27
0
파일: BifPoint.py 프로젝트: mdlama/pydstool
    def __locate_newton(self, X, C):
        """Note:  This is redundant!! B is a column of A!!!  Works for now, though..."""
        pind = self.testfuncs[0].pind

        J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords)
        J_params = C.CorrFunc.jac(X[0:C.dim], C.params)

        A = c_[J_coords, J_params[:,pind]]
        B = J_params[:,pind]

        return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \
                  matrixmultiply(transpose(A),X[C.dim+1:]), \
                  matrixmultiply(transpose(X[C.dim+1:]),B), \
                  matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1]
예제 #28
0
def test_module():
    import random
    import AtomMath
    import FileIO
    import Structure
    
    R = AtomMath.rmatrixu(numpy.array((0.0, 0.0, 1.0), float), math.pi/2.0)

    struct1 = FileIO.LoadStructure(fil="/home/jpaint/8rxn/8rxn.pdb")
    struct2 = FileIO.LoadStructure(fil="/home/jpaint/8rxn/8rxn.pdb")

    chn1 = struct1.get_chain("A")
    chn2 = struct2.get_chain("A")

    rc = lambda: 0.1 * (random.random() - 1.0)
    for atm in chn2.iter_atoms():
        atm.position = numpy.matrixmultiply(R, atm.position) + numpy.array((rc(),rc(),rc()),float)
        
    alist = []
 
    for atm1 in chn1.iter_atoms():
        if atm1.name != "CA":
            continue

        atm2 = chn2.get_equivalent_atom(atm1)
        if atm2 == None: continue

        alist.append((atm1, atm2))

    sup = SuperimposeAtoms(alist)

    R = sup.R
    Q = sup.Q
    print Q
    print R
    
    so = sup.src_origin
    do = sup.dst_origin
    
    sup1 = Structure.Structure(structure_id = "JMP1")
    for atm in chn1.iter_atoms():
        atm.position = numpy.matrixmultiply(R, atm.position - so)
        sup1.add_atom(atm)
    FileIO.SaveStructure(fil="super1.pdb", struct=sup1)

    sup2 = Structure.Structure(structure_id = "JMP2")
    for atm in chn2.iter_atoms():
        atm.position = atm.position - do
        sup2.add_atom(atm)
    FileIO.SaveStructure(fil="super2.pdb", struct=sup2)
예제 #29
0
    def __locate_newton(self, X, C):
        """Note:  This is redundant!! B is a column of A!!!  Works for now, though..."""
        pind = self.testfuncs[0].pind

        J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords)
        J_params = C.CorrFunc.jac(X[0:C.dim], C.params)

        A = c_[J_coords, J_params[:,pind]]
        B = J_params[:,pind]

        return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \
                  matrixmultiply(transpose(A),X[C.dim+1:]), \
                  matrixmultiply(transpose(X[C.dim+1:]),B), \
                  matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1]
예제 #30
0
    def svdClean(self, plane):
        global nturns, tx, ty
        print 'removing noise floor',plane
        
        if plane == 'x':
            b = tx[turn:,:]  #truncate by the first 5 turns
            n_turns = shape(b)[0]

        elif plane == 'y':
            b = ty[turn:,:]  #truncate by the first 5 turns
            n_turns = shape(b)[0]
        else:
            print "no tbt data acquired"
        
        b_mean = mean(b)
        b = (b-b_mean)/sqrt(n_turns)
        n_bpms = shape(b)[1]
        #----svd for matrix with bpms >10

        if n_bpms > 10:
            A = singular_value_decomposition(b,full_matrices=0)
            #print "Singular values:",A[1]
        else:
            sys.exit('Exit, # of bpms < 10')
        
        
        #----SVD cut for noise floor
        if sing_val > n_bpms:
            svdcut = n_bpms
            print 'requested more singular values than available'
            print '# of sing_val used for', plane, '=', n_bpms
        else:
            svdcut = int(sing_val)
            print '# of sing_val used for', plane, '=', svdcut
        #print A[1][0]
	A[1][svdcut:] = 0.
       	#temp=matrixmultiply(identity(len(A[1]))*A[1], A[2])
	temp=matrixmultiply(diag(A[1]), A[2])
	b = matrixmultiply(A[0],temp) ### check
        b = (b *sqrt(n_turns))+b_mean
        #b = b*sqrt(n_turns)
        
        if plane == 'x':
            tx[turn:,:] = b
        elif plane == 'y':
            ty[turn:,:] = b
        else:
            print "no tbt data to analyze"
        nturns = shape(tx)[0]
예제 #31
0
파일: misc.py 프로젝트: F-A/pydstool
def bialttoeig(q, p, n, A):
    v1, v2 = invwedge(q, n)
    w1, w2 = invwedge(p, n)

    A11 = bilinearform(A,v1,v1)
    A22 = bilinearform(A,v2,v2)
    A12 = bilinearform(A,v1,v2)
    A21 = bilinearform(A,v2,v1)
    v11 = matrixmultiply(transpose(v1),v1)
    v22 = matrixmultiply(transpose(v2),v2)
    v12 = matrixmultiply(transpose(v1),v2)
    D = v11*v22 - v12*v12
    k = (A11*A22 - A12*A21)/D

    return k[0][0], v1, w1
예제 #32
0
파일: misc.py 프로젝트: tclose/pydstool
def bialttoeig(q, p, n, A):
    v1, v2 = invwedge(q, n)
    w1, w2 = invwedge(p, n)

    A11 = bilinearform(A, v1, v1)
    A22 = bilinearform(A, v2, v2)
    A12 = bilinearform(A, v1, v2)
    A21 = bilinearform(A, v2, v1)
    v11 = matrixmultiply(transpose(v1), v1)
    v22 = matrixmultiply(transpose(v2), v2)
    v12 = matrixmultiply(transpose(v1), v2)
    D = v11 * v22 - v12 * v12
    k = (A11 * A22 - A12 * A21) / D

    return k[0][0], v1, w1
예제 #33
0
파일: BifPoint.py 프로젝트: mdlama/pydstool
    def process(self, X, V, C):
        BifPoint.process(self, X, V, C)

        # Finds the new branch
        J_coords = C.CorrFunc.jac(X, C.coords)
        J_params = C.CorrFunc.jac(X, C.params)


        singular = True
        perpvec = r_[1,zeros(C.dim-1)]
        d = 1
        while singular and d <= C.dim:
            try:
                v0 = linalg.solve(r_[c_[J_coords, J_params],
                                  [perpvec]], \
                                  r_[zeros(C.dim-1),1])
            except:
                perpvec = r_[0., perpvec[0:(C.dim-1)]]
                d += 1
            else:
                singular = False

        if singular:
            raise PyDSTool_ExistError("Problem in _compute: Failed to compute tangent vector.")
        v0 /= linalg.norm(v0)
        V = sign([x for x in v0 if abs(x) > 1e-8][0])*v0

        A = r_[c_[J_coords, J_params], [V]]
        W, VR = linalg.eig(A)
        W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5]
        V1 = real(VR[:,W0[0]])

        H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params)
        c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])])
        c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])])
        c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])])

        beta = 1
        alpha = -1*c22/(2*c12)
        V1 = alpha*V + beta*V1
        V1 /= linalg.norm(V1)

        self.found[-1].eigs = W
        self.found[-1].branch = todict(C, V1)

        self.info(C, -1)

        return True
예제 #34
0
        def mulXY(self, x, y):
            """Muliplies the matrix with each x/y element
	
			Arguments:
			x -- a sequence with x elements
			y -- a sequence with y elements
			"""
            start = time.time()
            length = min(len(x), len(y))
            w = numpy.ones(length, Float)

            #print x, y
            #for i in xrange(length):
            #	point = numpy.matrixmultiply(self.matrix, points[i])
            #	newx[i] = point[0] / point[2]
            #	newy[i] = point[1] / point[2]
            #end = time.time()
            #if end - start > 1.0:
            #	set_trace()
            x = numpy.array(x, numpy.Float)
            y = numpy.array(y, numpy.Float)
            points = numpy.matrixmultiply(self.matrix, array([x, y, w]))
            newx = points[0] / points[2]
            newy = points[1] / points[2]
            return newx, newy
def correctbeatEXP2(x,
                    x2,
                    y,
                    y2,
                    dx,
                    dx2,
                    beat_input2,
                    cut=0.01,
                    app=0,
                    path="./"):
    ###########################################################
    R = transpose(beat_input2.sensitivity_matrix)
    vector = beat_input2.computevectorEXP2(x, x2, y, y2, dx, dx2)
    wg = beat_input2.wg
    weisvec = array(
        concatenate([
            sqrt(wg[0]) *
            ones(len(beat_input2.phasexlist) + len(beat_input2.phasexlist2)),
            sqrt(wg[1]) *
            ones(len(beat_input2.phaseylist) + len(beat_input2.phaseylist2)),
            sqrt(wg[2]) *
            ones(len(beat_input2.betaxlist) + len(beat_input2.betaxlist2)),
            sqrt(wg[3]) *
            ones(len(beat_input2.betaylist) + len(beat_input2.betaylist2)),
            sqrt(wg[4]) *
            ones(len(beat_input2.displist) + len(beat_input2.displist2)),
            sqrt(wg[5]) * ones(4)
        ]))
    Rnew = transpose(transpose(R) * weisvec)
    #print (vector-beat_input.zerovector) # Good line to debug big correction strs
    delta = -matrixmultiply(generalized_inverse(
        Rnew, cut), (vector - beat_input2.zerovector) / beat_input2.normvector)
    writeparams(delta, beat_input2.varslist, app, path)
    return [delta, beat_input2.varslist]
예제 #36
0
def numeric_gemm_var1_flat(A, B, C, mc, kc, nc, mr=1, nr=1):
    M, N = C.shape
    K = A.shape[0]

    mc = min(mc, M)
    kc = min(kc, K)
    nc = min(nc, N)

    tA = numpy.zeros((mc, kc), dtype=numpy.float)
    tB = numpy.zeros((kc, N), dtype=numpy.float)

    for k in range(0, K, kc):
        # Pack B into tB
        tB[:, :] = B[k:k + kc:, :]

        for i in range(0, M, mc):
            imc = i + mc
            # Pack A into tA
            tA[:, :] = A[i:imc, k:k + kc]

            for j in range(0, N):  # , nc):
                # Cj += ABj + Cj
                # jnc = j+nc
                ABj = numpy.matrixmultiply(tA, tB[:, j])
                numpy.add(C[i:imc:, j], ABj, C[i:imc:, j])

                # Store Caux into memory
    return
예제 #37
0
 def transform(self, position):
     """Transforms a source position to its aligned position.
     """
     position = position - self.src_origin
     position = numpy.matrixmultiply(self.R, position)
     position = position + self.dst_origin
     return position
예제 #38
0
def correctcouple(a, dispy, couple_input, cut=0.01, app=0, path="./"):
    
    sm = couple_input.sensitivity_matrix

    if np.count_nonzero(sm) < 1:
        raise ValueError('Sensitivity matrix has only zeros')
    
    R =  np.transpose(sm)
    vector=couple_input.computevector(a,dispy)
    wg=couple_input.wg
    
    weisvec = np.array(np.concatenate([
                                      np.sqrt(wg[0])*np.ones(len(couple_input.couplelist)),
                                      np.sqrt(wg[1])*np.ones(len(couple_input.couplelist)),
                                      np.sqrt(wg[2])*np.ones(len(couple_input.couplelist)),
                                      np.sqrt(wg[3])*np.ones(len(couple_input.couplelist)),
                                      np.sqrt(wg[4])*np.ones(len(couple_input.dispylist))
                                      ])
                      )
    Rnew = np.transpose(np.transpose(R)*weisvec)
    
    delta = -matrixmultiply(generalized_inverse(Rnew,cut), (vector-couple_input.zerovector)/couple_input.normvector)
    
    write_params(delta, couple_input.varslist, app,  path=path)
    
    return [delta, couple_input.varslist]
def rmatrixz(vec):
    """Return a rotation matrix which transforms the coordinate system
    such that the vector vec is aligned along the z axis.
    """
    u, v, w = normalize(vec)

    d = math.sqrt(u * u + v * v)

    if d != 0.0:
        Rxz = numpy.array(
            [[u / d, v / d, 0.0], [-v / d, u / d, 0.0], [0.0, 0.0, 1.0]],
            float)
    else:
        Rxz = numpy.identity(3, float)

    Rxz2z = numpy.array([[w, 0.0, -d], [0.0, 1.0, 0.0], [d, 0.0, w]], float)

    R = numpy.matrixmultiply(Rxz2z, Rxz)

    try:
        assert numpy.allclose(linalg.determinant(R), 1.0)
    except AssertionError:
        print "rmatrixz(%s) determinant(R)=%f" % (vec, linalg.determinant(R))
        raise

    return R
예제 #40
0
 def classify(self, vector):
     if self._should_normalise:
         vector = self._normalise(vector)
     if self._Tt != None:
         vector = numpy.matrixmultiply(self._Tt, vector)
     cluster = self.classify_vectorspace(vector)
     return self.cluster_name(cluster)
def correctcouple2(couple,
                   couple2,
                   dispy,
                   dispy2,
                   couple_input2,
                   cut=0.01,
                   app=0,
                   path="./"):
    ################################################
    R = transpose(couple_input.sensitivity_matrix2)
    vector = couple_input2.computevector2(couple, couple2, dispy, dispy2)
    wg = couple_input2.wg
    weisvec = array(
        concatenate([
            sqrt(wg[0]) * ones(len(couple_input2.couplelist)),
            sqrt(wg[0]) * ones(len(couple_input2.couplelist2)),
            sqrt(wg[1]) * ones(len(couple_input2.couplelist)),
            sqrt(wg[1]) * ones(len(couple_input2.couplelist2)),
            sqrt(wg[2]) * ones(len(couple_input2.couplelist)),
            sqrt(wg[2]) * ones(len(couple_input2.couplelist2)),
            sqrt(wg[3]) * ones(len(couple_input2.couplelist)),
            sqrt(wg[3]) * ones(len(couple_input2.couplelist2)),
            sqrt(wg[4]) * ones(len(couple_input2.dispylist)),
            sqrt(wg[4]) * ones(len(couple_input2.dispylist2))
        ]))
    Rnew = transpose(transpose(R) * weisvec)
    delta = -matrixmultiply(
        generalized_inverse(Rnew, cut),
        (vector - couple_input2.zerovector) / couple_input2.normvector)
    writeparams(delta, couple_input2.varslist, app, path=path)
    return [delta, couple_input2.varslist]
예제 #42
0
 def transform(self, position):
     """Transforms a source position to its aligned position.
     """
     position = position - self.src_origin
     position = numpy.matrixmultiply(self.R, position)
     position = position + self.dst_origin
     return position
예제 #43
0
def eigenvector_for_largest_eigenvalue(matrix):
    """Returns eigenvector corresponding to largest eigenvalue of matrix.
    
    Implements a numerical method for finding an eigenvector by repeated 
    application of the matrix to a starting vector. For a matrix A the 
    process w(k) <-- A*w(k-1) converges to eigenvector w with the largest 
    eigenvalue. Because distance matrix D has all entries >= 0, a theorem 
    due to Perron and Frobenius on nonnegative matrices guarantees good 
    behavior of this method, excepting degenerate cases where the 
    iteration oscillates. For distance matrices a remedy is to add the 
    identity matrix to A, permitting the iteration to converge to the 
    eigenvector. (From Sander and Schneider (1991), and Vingron and 
    Sibbald (1993)) 
    
    Note: Only works on square matrices.
    """
    #always add the identity matrix to avoid oscillating behavior
    matrix = matrix + identity(len(matrix))

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

    #iterate until convergence
    for i in range(1000):
        new_v = matrixmultiply(matrix,v)
        new_v = new_v/sum(new_v, 0) #normalize
        if sum(list(map(abs,new_v-v)), 0) > 1e-9:
            v = new_v #not converged yet
            continue
        else: #converged
            break
    
    return new_v
예제 #44
0
 def func(self, X, V):
     H = self.F.sysfunc.hess(X, self.F.coords, self.F.coords)
     v = self.F.testfunc.data.v
     w = self.F.testfunc.data.w
     return array(matrixmultiply(transpose(w), reshape([bilinearform(H[i,:,:], v, v) \
                                                        for i in range(H.shape[0])],(H.shape[0],1)))[0])
     """This commented text is normal form information (I think).  It's a temporary commment.  Delete when comfortable."""
예제 #45
0
def correctcouple(a, dispy, couple_input, cut=0.01, app=0, path="./"):

    sm = couple_input.sensitivity_matrix

    if np.count_nonzero(sm) < 1:
        raise ValueError('Sensitivity matrix has only zeros')

    R = np.transpose(sm)
    vector = couple_input.computevector(a, dispy)
    wg = couple_input.wg

    weisvec = np.array(
        np.concatenate([
            np.sqrt(wg[0]) * np.ones(len(couple_input.couplelist)),
            np.sqrt(wg[1]) * np.ones(len(couple_input.couplelist)),
            np.sqrt(wg[2]) * np.ones(len(couple_input.couplelist)),
            np.sqrt(wg[3]) * np.ones(len(couple_input.couplelist)),
            np.sqrt(wg[4]) * np.ones(len(couple_input.dispylist))
        ]))
    Rnew = np.transpose(np.transpose(R) * weisvec)

    delta = -matrixmultiply(
        generalized_inverse(Rnew, cut),
        (vector - couple_input.zerovector) / couple_input.normvector)

    write_params(delta, couple_input.varslist, app, path=path)

    return [delta, couple_input.varslist]
예제 #46
0
파일: util.py 프로젝트: sergeyromanov/nltk
 def classify(self, vector):
     if self._should_normalise:
         vector = self._normalise(vector)
     if self._Tt != None:
         vector = numpy.matrixmultiply(self._Tt, vector)
     cluster = self.classify_vectorspace(vector)
     return self.cluster_name(cluster)
예제 #47
0
def eigenvector_for_largest_eigenvalue(matrix):
    """Returns eigenvector corresponding to largest eigenvalue of matrix.
    
    Implements a numerical method for finding an eigenvector by repeated 
    application of the matrix to a starting vector. For a matrix A the 
    process w(k) <-- A*w(k-1) converges to eigenvector w with the largest 
    eigenvalue. Because distance matrix D has all entries >= 0, a theorem 
    due to Perron and Frobenius on nonnegative matrices guarantees good 
    behavior of this method, excepting degenerate cases where the 
    iteration oscillates. For distance matrices a remedy is to add the 
    identity matrix to A, permitting the iteration to converge to the 
    eigenvector. (From Sander and Schneider (1991), and Vingron and 
    Sibbald (1993)) 
    
    Note: Only works on square matrices.
    """
    #always add the identity matrix to avoid oscillating behavior
    matrix = matrix + identity(len(matrix))

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

    #iterate until convergence
    for i in range(1000):
        new_v = matrixmultiply(matrix, v)
        new_v = new_v / sum(new_v, 0)  #normalize
        if sum(map(abs, new_v - v), 0) > 1e-9:
            v = new_v  #not converged yet
            continue
        else:  #converged
            break

    return new_v
예제 #48
0
def numeric_gemm_var1_flat(A, B, C, mc, kc, nc, mr=1, nr=1):
  M, N = C.shape
  K = A.shape[0]

  mc = min(mc, M)
  kc = min(kc, K)
  nc = min(nc, N)  

  tA = numpy.zeros((mc, kc), dtype = numpy.float)
  tB = numpy.zeros((kc, N), dtype = numpy.float)  

  for k in range(0, K, kc):
    # Pack B into tB
    tB[:,:] = B[k:k+kc:,:]
    
    for i in range(0, M, mc):
      imc = i+mc
      # Pack A into tA
      tA[:,:] = A[i:imc,k:k+kc]
      
      for j in range(0, N): # , nc):
        # Cj += ABj + Cj
        # jnc = j+nc
        ABj = numpy.matrixmultiply(tA, tB[:,j])
        numpy.add(C[i:imc:,j], ABj, C[i:imc:,j])
        
        # Store Caux into memory
  return
예제 #49
0
def correctbeatEXP(x,
                   y,
                   dx,
                   beat_input,
                   cut=0.01,
                   app=0,
                   path="./",
                   xbet=[],
                   ybet=[]):
    R = np.transpose(beat_input.sensitivity_matrix)
    vector = beat_input.computevectorEXP(x, y, dx, xbet, ybet)
    wg = beat_input.wg
    weisvec = np.array(
        np.concatenate([
            np.sqrt(wg[0]) * np.ones(len(beat_input.phasexlist)),
            np.sqrt(wg[1]) * np.ones(len(beat_input.phaseylist)),
            np.sqrt(wg[2]) * np.ones(len(beat_input.betaxlist)),
            np.sqrt(wg[3]) * np.ones(len(beat_input.betaylist)),
            np.sqrt(wg[4]) * np.ones(len(beat_input.displist)),
            np.sqrt(wg[5]) * np.ones(2)
        ]))
    Rnew = np.transpose(np.transpose(R) * weisvec)
    delta = -matrixmultiply(generalized_inverse(
        Rnew, cut), (vector - beat_input.zerovector) / beat_input.normvector)
    writeparams(delta, beat_input.varslist, app, path)
    return [delta, beat_input.varslist]
예제 #50
0
def itrSVD(X, Y, DX, beat_input, cut=0.001, num_iter=1, app=0, tol=1e-9, path="./"):
    R = np.transpose(beat_input.sensitivity_matrix)
    b = beat_input.computevectorEXP(X, Y, DX) - beat_input.zerovector
    corr = beat_input.varslist
    inva = generalized_inverse(R, cut)
    rmss, ptopp = calcRMSNumeric(b)
    RHO2 = {}
    dStren = np.zeros(len(corr))
    print 'Initial Phase-Beat:', '{RMS,PK2PK}', rmss, ptopp
    for ITER in range(num_iter):  # @UnusedVariable
        dStren = dStren + matrixmultiply(inva, b)
        bvec = b - matrixmultiply(R, dStren)
        rm, ptp = calcRMSNumeric(bvec)
        print 'ITER', num_iter, '{RMS,PK2PK}', rm, ptp
    for j in range(len(corr)):
        RHO2[corr[j]] = dStren[j]
    wrtpar(corr, RHO2, app, path)
예제 #51
0
파일: TestFunc.py 프로젝트: F-A/pydstool
    def func(self, X, V):
        H = self.F.sysfunc.hess(X, self.F.coords, self.F.coords)
        v = self.F.testfunc.data.v
        w = self.F.testfunc.data.w
        return array(matrixmultiply(transpose(w), reshape([bilinearform(H[i,:,:], v, v) \
                                                           for i in range(H.shape[0])],(H.shape[0],1)))[0])

        """This commented text is normal form information (I think).  It's a temporary commment.  Delete when comfortable."""
예제 #52
0
    def do_svd_clean(self, plane):
        """Does a SVD clean on the given plane"""
        time_start = time.time()
        print "(plane", plane, ") removing noise floor with SVD"

        A = numpy.array(self.sddsfile.dictionary_plane_to_bpms[plane].bpm_data)
        number_of_bpms = A.shape[0]

        if number_of_bpms <= 10:
            sys.exit("Number of bpms <= 10")

        # normalise the matrix
        sqrt_number_of_turns = numpy.sqrt(A.shape[1])
        A_mean = numpy.mean(A)
        A = (A - A_mean) / sqrt_number_of_turns

        if PRINT_TIMES:
            print ">>Time for svdClean (before SVD call):", time.time() - time_start, "s"
        USV = self.get_singular_value_decomposition(A)
        if PRINT_TIMES:
            print ">>Time for svdClean (after SVD call): ", time.time() - time_start, "s"

        # remove bad BPM by SVD (tbach)
        goodbpm_indices = self.get_badbpm_indices(USV, plane)
        USV = (USV[0][goodbpm_indices], USV[1], USV[2])
        number_of_bpms = len(goodbpm_indices)

        #----SVD cut for noise floor
        if _InputData.sing_val < number_of_bpms:
            print "(plane", plane, ") svdcut:", _InputData.sing_val
            USV[1][_InputData.sing_val:] = 0
        else:
            print "requested more singular values than available"

        A = matrixmultiply(USV[0], matrixmultiply(numpy.diag(USV[1]), USV[2]))
        # A0 * (A1 * A2) should require less operations than (A0 * A1) * A2,
        #  because of the different sizes
        # A0 has (M, K), A1 has (K, K) and A2 has (K, N) with K=min(M,N)
        # Most of the time, the number of turns is greater then
        #  the number of BPM, so M > N
        # --tbach
        A = (A * sqrt_number_of_turns) + A_mean
        self.sddsfile.dictionary_plane_to_bpms[plane].bpm_data = A
        if PRINT_TIMES:
            print ">>Time for do_svd_clean:", time.time() - time_start, "s"
예제 #53
0
파일: util.py 프로젝트: sergeyromanov/nltk
 def vector(self, vector):
     """
     Returns the vector after normalisation and dimensionality reduction
     """
     if self._should_normalise:
         vector = self._normalise(vector)
     if self._Tt != None:
         vector = numpy.matrixmultiply(self._Tt, vector)
     return vector
예제 #54
0
파일: misc.py 프로젝트: F-A/pydstool
def firstlyapunov(X, F, w, J_coords=None, V=None, W=None, p=None, q=None,
                  check=False):
    if J_coords is None:
        J_coords = F.jac(X, F.coords)

    if p is None:
        alpha = bilinearform(transpose(J_coords),V[:,0],V[:,1]) - \
                1j*w*matrixmultiply(V[:,0],V[:,1])
        beta = -1*bilinearform(transpose(J_coords),V[:,0],V[:,0]) + \
                1j*w*matrixmultiply(V[:,0],V[:,0])
        q = alpha*V[:,0] + beta*V[:,1]

        alpha = bilinearform(J_coords,W[:,0],W[:,1]) + \
                1j*w*matrixmultiply(W[:,0],W[:,1])
        beta = -1*bilinearform(J_coords,W[:,0],W[:,0]) - \
                1j*w*matrixmultiply(W[:,0],W[:,0])
        p = alpha*W[:,0] + beta*W[:,1]

        p /= linalg.norm(p)
        q /= linalg.norm(q)

        direc = conjugate(1/matrixmultiply(conjugate(p),q))
        p = direc*p

    if check:
        print('Checking...')
        print('  |q| = %f' % linalg.norm(q))
        temp = matrixmultiply(conjugate(p),q)
        print('  |<p,q> - 1| = ', abs(temp-1))
        print('  |Aq - iwq| = %f' % linalg.norm(matrixmultiply(J_coords,q) - 1j*w*q))
        print('  |A*p + iwp| = %f\n' % linalg.norm(matrixmultiply(transpose(J_coords),p) + 1j*w*p))

    # Compute first lyapunov coefficient
    B = F.hess(X, F.coords, F.coords)
    D = hess3(F, X, F.coords)
    b1 = array([bilinearform(B[i,:,:], q, q) for i in range(B.shape[0])])
    b2 = array([bilinearform(B[i,:,:], conjugate(q),
                          linalg.solve(2*1j*w*eye(F.m) - J_coords, b1)) \
                 for i in range(B.shape[0])])
    b3 = array([bilinearform(B[i,:,:], q, conjugate(q)) \
                 for i in range(B.shape[0])])
    b4 = array([bilinearform(B[i,:,:], q, linalg.solve(J_coords, b3)) \
                 for i in range(B.shape[0])])
    temp = array([trilinearform(D[i,:,:,:],q,q,conjugate(q)) \
                 for i in range(D.shape[0])]) + b2 - 2*b4

    l1 = 0.5*real(matrixmultiply(conjugate(p), temp))

    return l1
예제 #55
0
def test(algs, niters = 5, validate = False):
  """
  Test a numcer of algorithms and return the results.
  """

  if type(algs) is not list:
    algs = [algs]

  results = []
  m,n,k = (64,64,64)

  # Cache effects show up between 2048 and 4096 on a G4
  tests = [8, 16, 32, 64] # , 128, 256, 512, 768, 1024, 2048, 4096]: [2048, 4096]: #
  tests = [128, 256, 512, 1024, 2048, 4096]
  # tests = [4096]
  # tests = [2048]
  # tests = [512] 
  for size in tests: 
    m,n,k = (size, size, size)
    A, B, C = create_matrices(m, k, n)

    if validate:
      C_valid = numpy.matrixmultiply(A, B)

    for alg in algs:
      print alg.func_name, size
      if validate:
        alg(A, B, C)
        _validate(alg.func_name, m, n, k, C, C_valid)

      # KC = [32, 64, 128, 256] # , 512]
      KC = [32, 64, 128, 256] # , 256] # , 512]      
      # KC = [64]
      KC = [128, 256]
      KC = [256]
      NC = [32, 64, 128, 256] # , 512]
      # NC = [32, 32, 32] 
      # NC = [256, 256, 256]
      # NC = [128, 128, 128]
      NC = [128, 256]
      NC = [128]

      for mc in [32]: # , 64, 128, 256]:
        for kc in KC:
          for nc in NC:
            # print '  ', mc, kc, nc
            # try:
            if True:
              times = run_alg(alg, A, B, C, mc, kc, nc, 4, 4, niters)
              result = _result(alg.func_name, m, k, n, mc, kc, nc, times)
              results.append(result)
              print result
            # except:
            #   print 'Failed: ', alg.func_name, m, k, n, mc, kc, nc, times

  return results