Ejemplo n.º 1
0
def gradient_descent(X, Y, iter, alpha):
    (rows, cols) = X.shape
    Xt = X.T
    w = numpy.zeros((len(Xt), 1))
    print w.shape
    bar = Bar('iterations', max=iter)
    for i in range(0, iter):
        pw = w
        dw =  2*matrix.dot(matrix.dot(Xt,X), w) - matrix.dot(Xt, Y)

        # if (True):
        #     # print "alpha " + str(alpha)
        #     # print "E is " + str(dw.T.dot(dw).sum())
        #     # print dw
        #     print w
        w = w - alpha*dw/rows
        diff =numpy.absolute(w-pw).sum()
        print "Diff is %f " % diff
        if (diff < 0.000001):
            bar.finish()
            return w

        # raw_input()
        bar.next()
    bar.finish()
    return w
Ejemplo n.º 2
0
def get_basis(r_ij, r_kl):
    """
    Returns a list of vectors corresponding to an orthonormal basis
    given two orthogonal vectors r_ij and r_kl
    """

    e = []

    e.append(r_ij / math.sqrt(float(matrix.dot(r_ij, r_ij.T))))
    e.append(r_kl / math.sqrt(float(matrix.dot(r_kl, r_kl.T))))
    e.append(get_normal(r_ij, r_kl))

    return e
Ejemplo n.º 3
0
def transform_translate(e_prime, r_trans, point_set):

    # calculate transformation matrix elements L_ij
    e = []
    e.append(matrix([[1.0, 0.0, 0.0]]))
    e.append(matrix([[0.0, 1.0, 0.0]]))
    e.append(matrix([[0.0, 0.0, 1.0]]))

    L = numpy.zeros(shape=(3, 3))

    for i in range(0, len(e_prime)):
        for j in range(0, len(e)):
            L_ij = float(matrix.dot(e_prime[i], e[j].T))
            L[i][j] = L_ij

    new_set = []

    for r in point_set:

        # Rotate about the origin
        r = r * L

        # Translate
        r += r_trans

        new_set.append(r)

    return new_set
Ejemplo n.º 4
0
def get_normal(r_ij, r_kl):
    """
    Returns unit vector normal to vector r_ij and r_kl
    """
    n = numpy.cross(r_ij, r_kl)
    n = n / math.sqrt(float(matrix.dot(n, n.T)))

    return n
Ejemplo n.º 5
0
def gradient_descent(X, Y, iter, alpha, lamb=0):
    (rows, cols) = X.shape
    Xt = X.T
    w = numpy.zeros((len(Xt), 1))
    print w.shape
    bar = Bar("iterations", max=iter)
    for i in range(0, iter):
        pw = w
        dw = 2 * (matrix.dot(matrix.dot(Xt, X), w) - matrix.dot(Xt, Y)) + 2 * lamb * w
        # print w
        w = w - alpha * dw / rows
        diff = numpy.absolute(w - pw).sum()
        # print "Diff is %f " % diff
        if diff < 0.000001:
            bar.finish()
            return w

        bar.next()
    bar.finish()
    return w
Ejemplo n.º 6
0
def buildDirectInfoMatrix(msa,
                          seqid=.8,
                          pseudo_weight=.5,
                          refine=False,
                          **kwargs):
    """Returns direct information matrix calculated for *msa*, which may be an
    :class:`.MSA` instance or a 2D Numpy character array.

    Sequences sharing sequence identity of *seqid* or more with another
    sequence are regarded as similar sequences for calculating their weights
    using :func:`.calcMeff`.

    *pseudo_weight* are the weight for pseudo count probability.

    Sequences are not refined by default. When *refine* is set **True**,
    the MSA will be refined by the first sequence and the shape of direct
    information matrix will be smaller.
    """

    msa = getMSA(msa)
    from .msatools import msadipretest, msadirectinfo1, msadirectinfo2
    from numpy import matrix

    LOGGER.timeit('_di')
    if msa.shape[0] < 250:
        LOGGER.warning(
            'DI performs the best with higher number of sequences, and '
            'minimal number of sequences is recommended as 250.')
    refine = 1 if refine else 0
    # msadipretest get some parameter from msa to set matrix size
    length, q = msadipretest(msa, refine=refine)
    c = matrix.dot(matrix(zeros((length * q, 1), float)),
                   matrix(zeros((1, length * q), float)))
    prob = zeros((length, q + 1), float)
    # msadirectinfo1 return c to be inversed and prob to be used
    meff, n, length, c, prob = msadirectinfo1(msa,
                                              c,
                                              prob,
                                              theta=1. - seqid,
                                              pseudocount_weight=pseudo_weight,
                                              refine=refine,
                                              q=q + 1)

    c = c.I

    di = zeros((length, length), float)
    # get final DI
    di = msadirectinfo2(n, length, c, prob, di, q + 1)
    del prob, c
    LOGGER.report('DI matrix was calculated in %.2fs.', '_di')
    return di
Ejemplo n.º 7
0
def buildDI(msa, seqid=.8, pseudo_weight=.5, refine=False,
            **kwargs):
    """Return direct information matrix calculated for *msa*, which may be an
    :class:`.MSA` instance or a 2D Numpy character array.

    Sequences sharing sequence identity of *seqid* or more with another
    sequence are regarded as similar sequences for calculating their weights
    using :func:`.calcMeff`.

    *pseudo_weight* are the weight for pseudo count probability.

    Sequences are not refined by default. When *refine* is set **True**,
    the MSA will be refined by the first sequence and the shape of direct
    information matrix will be smaller.

    [WM09] Weigt, Martin, et al. "Identification of direct residue contacts
    in protein–protein interaction by message passing." Proceedings of the
    National Academy of Sciences 106.1 (2009): 67-72.

    [MF11] Morcos, Faruck, et al. "Direct-coupling analysis of residue
    coevolution captures native contacts across many protein families."
    Proceedings of the National Academy of Sciences 108.49
    (2011): E1293-E1301."""

    msa = getMSA(msa)

    from numpy import zeros
    from .Ccorrelation import msadipretest, msadirectinfo1, msadirectinfo2
    from numpy import matrix
    from ..Application.math import invsp

    refine = 1 if refine else 0
    # msadipretest get some parameter from msa to set matrix size
    length, q = msadipretest(msa, refine=refine)
    c = matrix.dot(matrix(zeros((length * q, 1), float)),
                   matrix(zeros((1, length * q), float)))
    prob = zeros((length, q + 1), float)
    # msadirectinfo1 return c to be inversed and prob to be used
    meff, n, length, c, prob = msadirectinfo1(msa, c, prob, theta=1. - seqid,
                                              pseudocount_weight=pseudo_weight,
                                              refine=refine, q=q + 1)

    c = invsp(c)

    di = zeros((length, length), float)
    # get final DI
    di = msadirectinfo2(n, length, c, prob, di, q + 1)
    del prob, c

    return di
Ejemplo n.º 8
0
    def mul_on_matrix(self, matrix):
        '''
        Умножение вектора на матрицу
        '''

        if not isinstance(matrix, Matrix):
            raise TypeError('Второй аргумент не является матрицей')
        else:
            if self.len != len(matrix.A[0]):
                raise ValueError('Не совпадает длина')
            else:
                return Vector(
                    matrix.dot(
                        self.__data
                    )
                )
Ejemplo n.º 9
0
def buildDirectInfoMatrix(msa, seqid=0.8, pseudo_weight=0.5, refine=False, **kwargs):
    """Returns direct information matrix calculated for *msa*, which may be an
    :class:`.MSA` instance or a 2D Numpy character array.

    Sequences sharing sequence identity of *seqid* or more with another
    sequence are regarded as similar sequences for calculating their weights
    using :func:`.calcMeff`.

    *pseudo_weight* are the weight for pseudo count probability.

    Sequences are not refined by default. When *refine* is set **True**,
    the MSA will be refined by the first sequence and the shape of direct
    information matrix will be smaller.
    """

    msa = getMSA(msa)
    from .msatools import msadipretest, msadirectinfo1, msadirectinfo2
    from numpy import matrix

    LOGGER.timeit("_di")
    if msa.shape[0] < 250:
        LOGGER.warning(
            "DI performs the best with higher number of sequences, and "
            "minimal number of sequences is recommended as 250."
        )
    refine = 1 if refine else 0
    # msadipretest get some parameter from msa to set matrix size
    length, q = msadipretest(msa, refine=refine)
    c = matrix.dot(matrix(zeros((length * q, 1), float)), matrix(zeros((1, length * q), float)))
    prob = zeros((length, q + 1), float)
    # msadirectinfo1 return c to be inversed and prob to be used
    meff, n, length, c, prob = msadirectinfo1(
        msa, c, prob, theta=1.0 - seqid, pseudocount_weight=pseudo_weight, refine=refine, q=q + 1
    )

    c = c.I

    di = zeros((length, length), float)
    # get final DI
    di = msadirectinfo2(n, length, c, prob, di, q + 1)
    del prob, c
    LOGGER.report("DI matrix was calculated in %.2fs.", "_di")
    return di
Ejemplo n.º 10
0
def matrix_array_multiply_and_format(matrix, array):
    unformated = matrix.dot(array).tolist()[0]
    return [str(bit % 2) for bit in unformated]
    for j in range(0,10):
        if(i-j)>=0:
            A_v[i,j]=1
            A_p[i,j]=(i-j)+0.5
        else:
            A_v[i,j]=0
            A_p[i,j]=0

#Creación y transposición del vector objetivo a lograr
y_obj_=np.array([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0])[np.newaxis]
y_obj=y_obj_.T

#Creación de la matriz A global
A=np.concatenate((A_p,A_v),axis=0)
np.vstack((A_p,A_v))
#Creación de la pseudo-inversa
I=alg.pinv(A)
#Cálculo del vector de fuerzas
F=mat.dot(I,y_obj)

t=np.array([0,1,2,3,4,5,6,7,8,9,10])
p_graf=A_p*F
v_graf=A_v*F

p_graf=p_graf[np.newaxis]
p_graf=p_graf.T

plt.plot(t,p_graf)
#plt.plot(t,v_graf)

	def get_input_to_ik(self,point_in,target_frame = "gripper_finger_link"):
		mult = matrix.dot(self.get_tranformation_matrix_of_point(point_in),self.get_tranformation_matrix_tool_tip_to_arm_link_5(target_frame))
		return mult
Ejemplo n.º 13
0
 def get_input_to_ik(self, point_in, target_frame="gripper_finger_link"):
     mult = matrix.dot(
         self.get_tranformation_matrix_of_point(point_in),
         self.get_tranformation_matrix_tool_tip_to_arm_link_5(target_frame))
     return mult
Ejemplo n.º 14
0
def matrix_array_multiply_and_format(matrix, array):
    unformated = matrix.dot(array).tolist()[0]
    return [str(bit % 2) for bit in unformated]