Exemple #1
0
    def test_basic_function_with_three_arguments(self):
        # multi_dot with three arguments uses a fast hand coded algorithm to
        # determine the optimal order. Therefore test it separately.
        A = np.random.random((6, 2))
        B = np.random.random((2, 6))
        C = np.random.random((6, 2))

        assert_almost_equal(multi_dot([A, B, C]), A.dot(B).dot(C))
        assert_almost_equal(multi_dot([A, B, C]), np.dot(A, np.dot(B, C)))
Exemple #2
0
 def test_basic_function_with_dynamic_programing_optimization(self):
     # multi_dot with four or more arguments uses the dynamic programing
     # optimization and therefore deserve a separate
     A = np.random.random((6, 2))
     B = np.random.random((2, 6))
     C = np.random.random((6, 2))
     D = np.random.random((2, 1))
     assert_almost_equal(multi_dot([A, B, C, D]), A.dot(B).dot(C).dot(D))
Exemple #3
0
    def test_vector_as_first_argument(self):
        # The first argument can be 1-D
        A1d = np.random.random(2)  # 1-D
        B = np.random.random((2, 6))
        C = np.random.random((6, 2))
        D = np.random.random((2, 2))

        # the result should be 1-D
        assert_equal(multi_dot([A1d, B, C, D]).shape, (2,))
Exemple #4
0
    def test_vector_as_first_and_last_argument(self):
        # The first and last arguments can be 1-D
        A1d = np.random.random(2)  # 1-D
        B = np.random.random((2, 6))
        C = np.random.random((6, 2))
        D1d = np.random.random(2)  # 1-D

        # the result should be a scalar
        assert_equal(multi_dot([A1d, B, C, D1d]).shape, ())
Exemple #5
0
    def test_vector_as_last_argument(self):
        # The last argument can be 1-D
        A = np.random.random((6, 2))
        B = np.random.random((2, 6))
        C = np.random.random((6, 2))
        D1d = np.random.random(2)  # 1-D

        # the result should be 1-D
        assert_equal(multi_dot([A, B, C, D1d]).shape, (6,))
    def fit(self, X, y, inverse_covariance=None):
        if self.add_ones:
            X_ones = self.add_column_of_ones(X)
        else:
            X_ones = X
        # first add a column of all ones to X
        n, d = X_ones.shape
        # the big expensive step when d is large
        if inverse_covariance is None:
            outer_product = dot(X_ones.T, X_ones)
            if self.normalize_lambda:
                lambda_reg = self.lambda_reg * norm(outer_product)
            else:
                lambda_reg = self.lambda_reg

            for i in range(d - 1):
                # Replacing `outer_product + lambda_reg * eye(d)` with
                # a direct modification of the outer_product matrix
                #
                # We're trading a little more time spent in the Python
                # interpreter with a savings of allocated arrays.
                outer_product[i, i] += lambda_reg
            self.inverse_covariance = inv(outer_product)
        else:
            self.inverse_covariance = inverse_covariance
        # estimate of the parameters
        self.beta_estimate = multi_dot([self.inverse_covariance, X_ones.T, y])
        # now we need the estimate of the noise variance
        # reference: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/summary.lm.html
        pred = dot(X_ones, self.beta_estimate)
        # get the residual of the predictions and square it
        pred -= y
        pred **= 2
        sum_squared_residuals = pred.sum()
        self.sigma_squared_estimate = sum_squared_residuals / max((n - d), 1)
        self.covar = self.sigma_squared_estimate * self.inverse_covariance
    def eval_jac_eq(self):
        config = self.config
        t = self.t

        j0 = np.zeros((1,3),dtype=np.float64)
        j1 = self.Mbar_vbs_chassis_jcs_input_bearing[:,2:3]
        j2 = j1.T
        j3 = self.P_vbs_chassis
        j4 = A(j3).T
        j5 = self.P_rbs_input_shaft
        j6 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]
        j7 = B(j5,j6)
        j8 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]
        j9 = B(j5,j8)
        j10 = j6.T
        j11 = A(j5).T
        j12 = multi_dot([j10,j11])
        j13 = self.ubar_rbs_input_shaft_jcs_input_bearing
        j14 = B(j5,j13)
        j15 = self.ubar_vbs_chassis_jcs_input_bearing
        j16 = (self.R_rbs_input_shaft.T + -1*self.R_vbs_chassis.T + multi_dot([j13.T,j11]) + -1*multi_dot([j15.T,j4]))
        j17 = j8.T
        j18 = multi_dot([j17,j11])
        j19 = B(j3,j1)
        j20 = B(j3,j15)
        j21 = self.Mbar_vbs_chassis_jcs_input_bearing[:,0:1]
        j22 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]
        j23 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]
        j24 = np.eye(3, dtype=np.float64)
        j25 = self.Mbar_rbs_connect_shaft_jcs_input_connect[:,0:1]
        j26 = self.P_rbs_connect_shaft
        j27 = A(j26).T
        j28 = self.Mbar_rbs_input_shaft_jcs_input_connect[:,0:1]
        j29 = -1*j24
        j30 = self.P_rbs_output_shaft
        j31 = self.Mbar_rbs_connect_shaft_jcs_output_connect[:,0:1]
        j32 = self.Mbar_rbs_output_shaft_jcs_output_connect[:,0:1]
        j33 = A(j30).T
        j34 = self.Mbar_vbs_chassis_jcs_output_bearing[:,2:3]
        j35 = j34.T
        j36 = self.Mbar_rbs_output_shaft_jcs_output_bearing[:,0:1]
        j37 = self.Mbar_rbs_output_shaft_jcs_output_bearing[:,1:2]
        j38 = B(j3,j34)

        self.jac_eq_blocks = (j0,
        multi_dot([j2,j4,j7]),
        j0,
        multi_dot([j10,j11,j19]),
        j0,
        multi_dot([j2,j4,j9]),
        j0,
        multi_dot([j17,j11,j19]),
        j12,
        (multi_dot([j10,j11,j14]) + multi_dot([j16,j7])),
        -1*j12,
        -1*multi_dot([j10,j11,j20]),
        j18,
        (multi_dot([j17,j11,j14]) + multi_dot([j16,j9])),
        -1*j18,
        -1*multi_dot([j17,j11,j20]),
        j0,
        multi_dot([j21.T,j4,(cos(config.UF_mcs_hand_wheel(t))*B(j5,j22) + -1*sin(config.UF_mcs_hand_wheel(t))*B(j5,j23))]),
        j0,
        multi_dot([(cos(config.UF_mcs_hand_wheel(t))*multi_dot([j22.T,j11]) + -1*sin(config.UF_mcs_hand_wheel(t))*multi_dot([j23.T,j11])),B(j3,j21)]),
        j24,
        B(j5,self.ubar_rbs_input_shaft_jcs_input_connect),
        j29,
        -1*B(j26,self.ubar_rbs_connect_shaft_jcs_input_connect),
        j0,
        multi_dot([j25.T,j27,B(j5,j28)]),
        j0,
        multi_dot([j28.T,j11,B(j26,j25)]),
        j29,
        -1*B(j26,self.ubar_rbs_connect_shaft_jcs_output_connect),
        j24,
        B(j30,self.ubar_rbs_output_shaft_jcs_output_connect),
        j0,
        multi_dot([j32.T,j33,B(j26,j31)]),
        j0,
        multi_dot([j31.T,j27,B(j30,j32)]),
        j24,
        B(j30,self.ubar_rbs_output_shaft_jcs_output_bearing),
        j29,
        -1*B(j3,self.ubar_vbs_chassis_jcs_output_bearing),
        j0,
        multi_dot([j35,j4,B(j30,j36)]),
        j0,
        multi_dot([j36.T,j33,j38]),
        j0,
        multi_dot([j35,j4,B(j30,j37)]),
        j0,
        multi_dot([j37.T,j33,j38]),
        j0,
        2*j5.T,
        j0,
        2*j26.T,
        j0,
        2*j30.T,)
#Phase shifters' arguments
PHargs = [Pi / 4 + err[8], 0 + err[9], Pi / 4 + err[10], 0 + err[11]]

#Squeezing arguments
SQargs = [0.4 + err[12], 0 + err[13], 0 + err[14], 0.4 + err[15]]
#-----------------------------------#

#Generate total unitary matrix for BS, PH
UBS = beam_splitter_args(dim, BSargs, BeamS)
Uphase = np.diag([
    np.exp(PHargs[0] * 1j),
    np.exp(PHargs[1] * 1j),
    np.exp(PHargs[2] * 1j),
    np.exp(PHargs[3] * 1j)
])
U = multi_dot([UBS, Uphase])

#Open file to write data
file = open(filepath, "w")

#Initiate program
gbs = sf.Program(dim)

with gbs.context as q:
    # prepare the input squeezed states

    Sgate(SQargs[0]) | q[0]
    Sgate(SQargs[1]) | q[1]
    Sgate(SQargs[2]) | q[2]
    Sgate(SQargs[3]) | q[3]
Exemple #9
0
def proj_c(M, d):
    if (LA.matrix_rank(M) == 0): return (np.eye(d))
    return (np.eye(d) - LA.multi_dot([M.T, np.linalg.inv(M.dot(M.T)), M]))
Exemple #10
0
def example_2x2():
    """Reproduce example 2x2 image figure in paper"""
    np.random.seed(0)

    img = np.array([[11, 12], [21, 22]]).astype(np.float32)
    x = img.flatten().reshape(4, 1)
    D1 = keynet.dense.uniform_random_diagonal_matrix(4)
    P1 = keynet.dense.random_doubly_stochastic_matrix(4, 2)
    A1 = np.dot(D1, P1)
    A1inv = np.linalg.inv(A1)

    P2 = keynet.dense.random_permutation_matrix(4)
    D2 = keynet.dense.uniform_random_diagonal_matrix(4)
    A2 = np.dot(D2, P2)
    A2inv = np.linalg.inv(A2)

    W1 = np.array([[-1, 1, 0, 0], [0, -1, 0, 0], [0, 0, -1, 1],
                   [0, 0, 0, -1]]).astype(np.float32)
    W1hat = multi_dot((A2, W1, A1inv))

    print('img')
    print(img)

    print('x')
    print(x)

    print('D1')
    print(D1)
    print('P1')
    print(P1)
    print('A1')
    print(A1)

    print('W1')
    print(W1)
    print('W1hat')
    print(W1hat)

    print('A1inv*A1')
    print(np.dot(A1inv, A1))

    print('A2')
    print(A2)

    x1h = multi_dot((W1hat, A1, x))

    x2h = copy.deepcopy(x1h)
    x2h[x2h <= 0] = 0  # ReLU

    x1 = multi_dot((W1, x))
    x2 = copy.deepcopy(x1)
    x2[x2 <= 0] = 0  # ReLU

    print('A1*x, x1, x1h, x2, x2h, A2inv * x2h')
    print(multi_dot((A1, x)))
    print(x1)
    print(x1h)

    print(x2)
    print(x2h)
    print(multi_dot((A2inv, x2h)))
Exemple #11
0
def codebook_construct(X, threshold, k, l):
    (n, m) = X.shape
    
    #U: n \times k
    #S: k \times l  
    #V: m \times l
    #row: k (user_clusterN)
    #col: l (item_clusterN)
    
    #k-means (row in python)
    
    V_old = np.zeros(shape=(m, l))
    U_old = np.zeros(shape=(n, k))
    
    #V_old: item
    kmeans = KMeans(n_clusters=l, random_state=0).fit(np.transpose(X)) #X^T: m*n
    labels = kmeans.labels_           # 1*m
    
    for i in labels:
        V_old[i] = np.zeros(shape=(1, l))
        V_old[i][labels[i]] = 1
        
    tmp = np.zeros(shape=(m, l))      
    tmp.fill(0.2)
    V_old = np.add(V_old, tmp)    #V: m*l
    
    #U_old: user
    kmeans = KMeans(n_clusters=k, random_state=0).fit(X)              #X: n*m
    labels = kmeans.labels_           # 1*n
    
    for i in labels:
        U_old[i] = np.zeros(shape=(1, k))
        U_old[i][labels[i]] = 1
        
    tmp = np.zeros(shape=(n, k))      
    tmp.fill(0.2)
    U_old = np.add(U_old, tmp)      #U: n*k
    
    
    # S: k*l = k*n n*m m*l
    S_old = multi_dot([np.transpose(U_old), X, V_old])
    
    print('finish k-means')
    #print(V_old)
    #print(U_old)
    #print(S_old)
        
    
    eta = 10   #any number > threshold
    #t = 0
    while eta > threshold:
        up = multi_dot([np.transpose(X), U_old, S_old])
        down = multi_dot([V_old, np.transpose(V_old), np.transpose(X), U_old, S_old])
        V_new = np.sqrt(np.multiply(V_old, np.divide(up, down)))
        
        eta = squareSum(np.subtract(V_new, V_old))
        
        up = multi_dot([X, V_new, np.transpose(S_old)])
        down = multi_dot([U_old, np.transpose(U_old), X, V_new, np.transpose(S_old)])
        U_new = np.sqrt(np.multiply(U_old, np.divide(up, down)))
        
        eta += squareSum(np.subtract(U_new, U_old))
        
        up = multi_dot([np.transpose(U_new), X, V_new])
        down = multi_dot([np.transpose(U_new), U_new, S_old, np.transpose(V_new), V_new])
        S_new = np.sqrt(np.multiply(S_old, np.divide(up, down)))
        
        eta += squareSum(np.subtract(S_new, S_old))
        eta /= 3
        
        V_old = V_new
        U_old = U_new
        S_old = S_new
        #print(t, eta)
        #t += 1
        
    '''
    # check if U^TU=I, V^TV=I
    if np.array_equal(np.dot(np.transpose(U_old), U_old), np.identity(n)) == False:
        print('U^TU!=I')
        print(np.dot(np.transpose(U_old), U_old))
    
    if np.array_equal(np.dot(np.transpose(V_old), V_old), np.identity(m)) == False:
        print('V^TV!=I')
        print(np.dot(np.transpose(V_old), V_old))
    '''
    
    #print('U: ', U_new)
    #print('V: ', V_new)
    print('finish initialization')
        
    U_aux = np.zeros(shape=(n, k))
    V_aux = np.zeros(shape=(m, l))
    
    
    for i in range(n):
        j_max = np.argmax(U_new[i])
        U_aux[i] = np.zeros(shape=(1, k))
        U_aux[i][j_max] = 1
        #print('U: ', i, j_max)

    
    # remove zeroCol
    '''
    zeroCol = []
    for j in range(U_aux.shape[1]):
        if(np.sum(U_aux[:, j]) == 0):
            zeroCol.append(j)
            
    U_aux = np.delete(U_aux, zeroCol, axis=1)
    '''
    
    print('finish U_aux:\n', U_aux)
    
    
    for i in range(m):
        j_max = np.argmax(V_new[i])
        #print('V: ', i, j_max)
        V_aux[i] = np.zeros(shape=(1, l))
        V_aux[i][j_max] = 1

    #remove zeroCol
    '''
    zeroCol = []
    for i in range(V_aux.shape[0]):
        if(np.sum(V_aux[i]) == 0):
            # remove col
            zeroCol.append(i)
            
    V_aux = np.delete(V_aux, zeroCol, axis=0)
    '''
    #for i in range(V_aux.shape[0]):
        #print(i, np.sum(V_aux[i]))
            
    print('finish V_aux:\n', V_aux)
    
    
    
    
    one = np.zeros(shape=(n, 1))
    one.fill(1)
    one2 = np.zeros(shape=(1, m))
    one2.fill(1)
    #print(np.transpose(U_aux).shape, one.shape, one2.shape, V_aux.shape)
    up = multi_dot([np.transpose(U_aux), X, V_aux])
    down = multi_dot([np.transpose(U_aux), one, one2, V_aux])
    #print('up\n', up)
    #print('down\n', down)
    
    B = np.divide(up, down)
    print('Got B\n', B)
    
    # nan->0
    B = np.nan_to_num(B)
    return B
    def objective(self, param_values: np.ndarray) -> float:
        # rename parameters just to make shorter and make use of our dictionary
        thetas = param_values
        n = self._num_qubits
        d = int(2 ** n)
        cnots = self._cnots
        num_cnots = self.num_cnots

        # to save intermediate computations we define the following matrices
        # this is the collection of cnot unit matrices ordered from left to
        # right as in the circuit, not matrix product
        cnot_unit_collection = np.zeros((d, d * num_cnots), dtype=complex)
        # this is the collection of matrix products of the cnot units up
        # to the given position from the right of the circuit
        cnot_right_collection = np.zeros((d, d * num_cnots), dtype=complex)
        # this is the collection of matrix products of the cnot units up
        # to the given position from the left of the circuit
        cnot_left_collection = np.zeros((d, d * num_cnots), dtype=complex)
        # first, we construct each cnot unit matrix
        for cnot_index in range(num_cnots):
            theta_index = 4 * cnot_index

            # cnot qubit indices for the cnot unit identified by cnot_index
            q1 = int(cnots[0, cnot_index])
            q2 = int(cnots[1, cnot_index])

            # rotations that are applied on the q1 qubit
            ry1 = ry_matrix(thetas[0 + theta_index])
            rz1 = rz_matrix(thetas[1 + theta_index])

            # rotations that are applied on the q2 qubit
            ry2 = ry_matrix(thetas[2 + theta_index])
            rx2 = rx_matrix(thetas[3 + theta_index])

            # combine the rotations on qubits q1 and q2
            single_q1 = np.dot(rz1, ry1)
            single_q2 = np.dot(rx2, ry2)

            # we place single qubit matrices at the corresponding locations in the (2^n, 2^n) matrix
            full_q1 = place_unitary(single_q1, n, q1)
            full_q2 = place_unitary(single_q2, n, q2)

            # we place a cnot matrix at the qubits q1 and q2 in the full matrix
            cnot_q1q2 = place_cnot(n, q1, q2)

            # compute the cnot unit matrix and store in cnot_unit_collection
            cnot_unit_collection[:, d * cnot_index : d * (cnot_index + 1)] = la.multi_dot(
                [full_q2, full_q1, cnot_q1q2]
            )

        # this is the matrix corresponding to the intermediate matrix products
        # it will end up being the matrix product of all the cnot unit matrices
        # first we multiply from the right-hand side of the circuit
        cnot_matrix = np.eye(d)
        for cnot_index in range(num_cnots - 1, -1, -1):
            cnot_matrix = np.dot(
                cnot_matrix, cnot_unit_collection[:, d * cnot_index : d * (cnot_index + 1)]
            )
            cnot_right_collection[:, d * cnot_index : d * (cnot_index + 1)] = cnot_matrix
        # now we multiply from the left-hand side of the circuit
        cnot_matrix = np.eye(d)
        for cnot_index in range(num_cnots):
            cnot_matrix = np.dot(
                cnot_unit_collection[:, d * cnot_index : d * (cnot_index + 1)], cnot_matrix
            )
            cnot_left_collection[:, d * cnot_index : d * (cnot_index + 1)] = cnot_matrix

        # this is the matrix corresponding to the initial rotations
        # we start with 1 and kronecker product each qubit's rotations
        rotation_matrix = 1
        for q in range(n):
            theta_index = 4 * num_cnots + 3 * q
            rz0 = rz_matrix(thetas[0 + theta_index])
            ry1 = ry_matrix(thetas[1 + theta_index])
            rz2 = rz_matrix(thetas[2 + theta_index])
            rotation_matrix = np.kron(rotation_matrix, la.multi_dot([rz0, ry1, rz2]))

        # the matrix corresponding to the full circuit is the cnot part and
        # rotation part multiplied together
        circuit_matrix = np.dot(cnot_matrix, rotation_matrix)

        # compute error
        error = 0.5 * (la.norm(circuit_matrix - self._target_matrix, "fro") ** 2)

        # cache computations for gradient
        self._last_thetas = thetas
        self._cnot_left_collection = cnot_left_collection
        self._cnot_right_collection = cnot_right_collection
        self._rotation_matrix = rotation_matrix
        self._cnot_matrix = cnot_matrix

        return error
    def loop(self):
        # Attitude estimation
        self.F1[0:3, 3:6] = hat(self.x1_est[0:3, :])
        (self.F1d, self.B1d, self.H1, self.D1, self.dT) = cont2discrete(
            (self.F1, self.B1, self.H1, self.D1), self.dT)
        # predict
        self.x1_pre = np.dot(self.F1d, self.x1_est) + np.dot(self.B1d, self.u)
        self.P1_pre = multi_dot([self.F1d, self.P1_est, self.F1d.T]) + self.Q1

        # Kalman gain
        K1 = multi_dot([
            self.P1_pre, self.H1.T,
            inv(multi_dot([self.H1, self.P1_pre, self.H1.T]) + self.R1)
        ])

        # update
        y1 = self.z1 - np.dot(self.H1, self.x1_pre)
        self.x1_est = self.x1_pre + np.dot(K1, y1)
        self.x1_est[0:3, :] = self.x1_est[0:3, :] / norm(
            self.x1_est[0:3, :])  # normalization
        self.P1_est = np.dot(np.eye(6) - np.dot(K1, self.H1), self.P1_pre)

        # Orientation estimation
        self.F2[0:3, 3:6] = hat(self.x2_est[0:3, :])
        (self.F2d, self.B2d, self.H2, self.D2, self.dT) = cont2discrete(
            (self.F2, self.B2, self.H2, self.D2), self.dT)
        # predict
        self.x2_pre = np.dot(self.F2d, self.x2_est) + np.dot(self.B2d, self.u)
        self.P2_pre = multi_dot([self.F2d, self.P2_est, self.F2d.T]) + self.Q2

        # Kalman gain
        K2 = multi_dot([
            self.P2_pre, self.H2.T,
            inv(multi_dot([self.H2, self.P2_pre, self.H2.T]) + self.R2)
        ])

        # update
        y2 = self.z2 - np.dot(self.H2, self.x2_pre)
        self.x2_est = self.x2_pre + np.dot(K2, y2)
        self.x2_est[0:3, :] = self.x2_est[0:3, :] / norm(
            self.x2_est[0:3, :])  # normalization
        self.P2_est = np.dot(np.eye(6) - np.dot(K2, self.H2), self.P2_pre)
        '''
        self.F[0:3, 6:9] = hat(self.x_est[0:3, :])
        self.F[0:3, 9:12] = -hat(self.x_est[0:3, :])
        self.F[3:6, 6:9] = hat(self.x_est[3:6, :])
        self.F[3:6, 9:12] = -hat(self.x_est[3:6, :])
        '''

        # Direct Cosine Matrix
        C = np.array([
            np.cross(self.x1_est[0:3, :].T, self.x2_est[0:3, :].T)[0],
            self.x2_est[0:3, :].T[0], self.x1_est[0:3, :].T[0]
        ])
        (phi, theta, psi) = rotation2euler(C)  # convert to Euler angles

        # publish state
        self.attitude.x = phi
        self.attitude.y = theta
        self.attitude.z = psi
        self.attitude_pub.publish(self.attitude)

        self.r.sleep()
Rlambda, Reigvec = la.eig(R_T_R)  #finding the spectral decomp. of RtR

Rlambda = Rlambda.real
idx = np.argsort(Rlambda)[::-1]
Rlambda = Rlambda[idx]
Rsing = np.abs(np.sqrt(np.abs(Rlambda)))
D = np.diag(Rsing)  #Constructing the diagonal matrix
Reigvec1 = Reigvec[:, idx].real  #V matrix of right singular vectors
U = Rimg1.dot(Reigvec1)
for i in range(
        Rlambda.shape[0]):  #Construction the U matrix of left singular vectors
    U[:, i] = U[:, i] / Rsing[i]

k = min(150, len, wid)  #choosing the no. of singular values for compression
B = multi_dot([U[:, 0:k], D[0:k, 0:k], Reigvec1.T[0:k, :]
               ]) * 255  #SVD reconstruction with k nodes

MSEI = np.sum(np.square(orig_img - B)) / (len * wid)
MaxI = np.max(orig_img).astype('int32')
temp = np.square(MaxI) / MSEI
PSNR = 10 * np.log10(temp)  #computing Peak Signal to Noise Ratio
print("The MSE for image compression is :" + np.str(MSEI))
print("The max pixel value for image is :" + np.str(MaxI))
print("The Peak signal to noise ratio for compression is " + np.str(PSNR))

Noiseimg = np.abs(orig_img - B)

Image.fromarray(B).show()  #viewing the compressed reconstructed image

Image.fromarray(
    Noiseimg).show()  #viewing the Noise part of the image that is left over
Exemple #15
0
        L[0] - L[1] * np.sin(q[1]) - L[2] * np.sin(q[1] + q[2])])

def IK(x,l):
  x, y, z = x[0], x[1], x[2]

  a = (x ** 2 + y ** 2 + (z - l[0]) ** 2 - l[1] ** 2 - l[2] ** 2) / (2 * l[1] * l[2])
  b = - (np.sqrt(1 - a ** 2))

  q1 = np.arctan2(y, x)
  q2 = np.arctan2(z - l[0], np.sqrt(x ** 2 + y ** 2)) - np.arctan2(l[2] * b, l[1] + l[2] * a)
  q3 = np.arctan2(b, a)
  ik = np.array([q1,q2,q3])
  return ik

# Jacobian Skew theory
A1 = multi_dot([R_z(q1),T_z(l1)])
A2 = multi_dot([A1,R_y(q2),T_x(l2)])
A3 = multi_dot([A2,R_y(q3),T_x(l3)])

O_1 = A1[:3,3]
O_2 = A2[:3,3]
O_3 = A3[:3,3]

z1 = A1[:3, 2]
z2 = A2[:3, 2]
z3 = A3[:3, 2]

J1 = np.hstack(( np.cross(z1,(O_3 - O_1)),z1))
J2 = np.hstack(( np.cross(z2,(O_3 - O_2)),z2)) 
J3 = np.hstack(( np.cross(z3,(O_3 - O_3)),z3))
# -------
Exemple #16
0
def runScalenet(trainD,
                testD,
                yTrain,
                yTest,
                k,
                eta1,
                eta2,
                MaxIter=20,
                subMaxIter=6):
    error = 1e-3

    scaler = StandardScaler()
    trainD = scaler.fit_transform(trainD)
    testD = scaler.transform(testD)

    trainD = np.column_stack((trainD, np.ones(
        (trainD.shape[0])))).T  #add a feature for bias term
    testD = np.column_stack((testD, np.ones((testD.shape[0])))).T

    MTr = np.isnan(trainD)
    MTr = np.concatenate([~MTr, MTr], axis=0).astype(float)
    MTe = np.isnan(testD)
    MTe = np.concatenate([~MTe, MTe], axis=0).astype(float)
    trainD = np.nan_to_num(trainD)
    testD = np.nan_to_num(testD)
    dTrain = trainD.shape[0]
    nTrain = trainD.shape[1]
    PTr = MTr[:dTrain, :]
    '''
    initialize U and V
        
    '''
    U = np.zeros((k, dTrain))
    V = np.random.random((k, 2 * dTrain))

    I = np.identity(2 * dTrain)

    sv = getSupportV(yTrain, MTr, U, V, trainD)  ###   get support vectors

    obj0 = getobj(trainD, U, V, MTr, I, eta1, eta2, yTrain,
                  sv)  ### get obj values

    for maxIter in range(MaxIter):

        C = getC(V, eta1)
        L_phi = getL_phi(V, MTr, eta1, I, nTrain, PTr)
        L_h = getL_h(V, eta2, nTrain, MTr, trainD)
        gamma = max((8 * L_phi)**0.5, 8 * L_h)
        eps = obj0
        '''
        Calculate step and T(U), if T(U) > 50, we set 50 to the iteration number
        
        '''
        step = eps / (gamma * (eta2**0.5))

        if eta2 < 1:
            T_u = max(((8 * L_phi)**0.5 * C * gamma) / (3 * eps),
                      ((8 * L_h) * C * gamma) / eps)
        else:
            T_u = max(((8 * L_phi)**0.5 * eta2 * C * gamma) / (3 * eps),
                      ((8 * L_h) * eta2**0.5 * C * gamma) / eps)
        '''
        update U
        
        '''

        obj_best = obj0
        best_U = U
        best_V = V
        best_sv = sv

        for stage1 in range(subMaxIter):
            '''
            find best U
            '''

            T_u = min(T_u, 50)

            for t1 in range(int(math.ceil(T_u))):

                gU = multi_dot([
                    2 * V, eta1 * I, np.dot(V.T, U)
                ]) - (eta2 / nTrain) * multi_dot([
                    V, MTr.T[sv].T,
                    np.diag(yTrain[sv]), trainD.T[sv]
                ]) + (2 / nTrain) * multi_dot(
                    [V, MTr,
                     np.multiply(PTr.T, multi_dot([MTr.T, V.T, U]))])
                U = U - step * gU / (np.linalg.norm(gU, ord='fro'))

                sv = getSupportV(yTrain, MTr, U, V, trainD)
                obj_new = getobj(trainD, U, V, MTr, I, eta1, eta2, yTrain, sv)

                if obj_new <= obj_best:

                    obj_best = getobj(trainD, U, V, MTr, I, eta1, eta2, yTrain,
                                      sv)
                    best_U = U
                    best_sv = sv

            step = step / 2.
            T_u = T_u * 2
            U = best_U
            sv = best_sv
        '''
        update V
        '''
        eps = obj_best
        C = getC(U, eta1)
        L_phi = getL_phi(U, MTr, eta1, I, nTrain, PTr)
        L_h = getL_h(U, eta2, nTrain, MTr, trainD)

        gamma = max((8 * L_phi)**0.5, 8 * L_h)

        step = eps / (gamma * (eta2**0.5))

        if eta2 < 1:
            T_v = max(((8 * L_phi)**0.5 * C * gamma) / (3 * eps),
                      ((8 * L_h) * C * gamma) / eps)
        else:
            T_v = max(((8 * L_phi)**0.5 * eta2 * C * gamma) / (3 * eps),
                      ((8 * L_h) * eta2**0.5 * C * gamma) / eps)

        for stage2 in range(subMaxIter):
            '''
            find best V
            '''
            T_v = min(T_v, 50)

            for t2 in range(int(math.ceil(T_v))):

                gV = multi_dot([
                    multi_dot([2 * U, U.T, V]), eta1 * I
                ]) - (eta2 / nTrain) * multi_dot([
                    U, trainD.T[sv].T,
                    np.diag(yTrain[sv]), MTr.T[sv]
                ]) + (2 / nTrain) * multi_dot(
                    [U, np.multiply(PTr, multi_dot([U.T, V, MTr])), MTr.T])
                V = V - step * gV / (np.linalg.norm(gV, ord='fro'))

                sv = getSupportV(yTrain, MTr, U, V, trainD)

                obj_new = getobj(trainD, U, V, MTr, I, eta1, eta2, yTrain, sv)

                if obj_new <= obj_best:
                    obj_best = getobj(trainD, U, V, MTr, I, eta1, eta2, yTrain,
                                      sv)
                    best_V = V
                    best_sv = sv

            step = step / 2.
            T_v = T_v * 2
            V = best_V
            sv = best_sv

        obj = getobj(trainD, U, V, MTr, I, eta1, eta2, yTrain, sv)

        if abs(obj0 - obj) / (obj0) < error:
            break

        obj0 = obj
    '''
    test
    '''

    predict = np.sum(np.multiply(multi_dot([U.T, V, MTe]), testD), axis=0)
    predict[predict < 0] = -1
    predict[predict >= 0] = 1

    accuray = accuracy_score(yTest, predict)

    return accuray
def find_Kt(variance_belief, C, Ctranspose, Q):
    return multi_dot([
        variance_belief, Ctranspose,
        inv(multi_dot([C, variance_belief, Ctranspose]) + Q)
    ])
Exemple #18
0
def dots(*arg):
    return multi_dot(arg)
Exemple #19
0
def E_ln_mu_k(k, beta, m, W, nu, xn):
  # print('m, W\n', m, W)
  return D*beta[k]**-1 + nu[k]*multi_dot(((xn-m[k]), W[k], (xn-m[k]).T))
    def gradient(self, param_values: np.ndarray) -> np.ndarray:
        # just to make shorter
        thetas = param_values
        # if given thetas are the same as used at the previous objective computations, then
        # we re-use computations, otherwise we have to re-compute objective
        if not np.all(np.isclose(thetas, self._last_thetas)):
            self.objective(thetas)

        # the partial derivative of the circuit with respect to an angle
        # is the same circuit with the corresponding pauli gate, multiplied
        # by a global phase of -1j / 2, next to the rotation gate (it commutes)
        pauli_x = np.multiply(-1j / 2, np.array([[0, 1], [1, 0]]))
        pauli_y = np.multiply(-1j / 2, np.array([[0, -1j], [1j, 0]]))
        pauli_z = np.multiply(-1j / 2, np.array([[1, 0], [0, -1]]))

        n = self._num_qubits
        d = int(2 ** n)
        cnots = self._cnots
        num_cnots = self.num_cnots

        # the partial derivative of the cost function is -Re<V',U>
        # where V' is the partial derivative of the circuit
        # first we compute the partial derivatives in the cnot part
        der = np.zeros(4 * num_cnots + 3 * n)
        for cnot_index in range(num_cnots):
            theta_index = 4 * cnot_index

            # cnot qubit indices for the cnot unit identified by cnot_index
            q1 = int(cnots[0, cnot_index])
            q2 = int(cnots[1, cnot_index])

            # rotations that are applied on the q1 qubit
            ry1 = ry_matrix(thetas[0 + theta_index])
            rz1 = rz_matrix(thetas[1 + theta_index])

            # rotations that are applied on the q2 qubit
            ry2 = ry_matrix(thetas[2 + theta_index])
            rx2 = rx_matrix(thetas[3 + theta_index])

            # combine the rotations on qubits q1 and q2
            # note we have to insert an extra pauli gate to take the derivative
            # of the appropriate rotation gate
            for i in range(4):
                if i == 0:
                    single_q1 = la.multi_dot([rz1, pauli_y, ry1])
                    single_q2 = np.dot(rx2, ry2)
                elif i == 1:
                    single_q1 = la.multi_dot([pauli_z, rz1, ry1])
                    single_q2 = np.dot(rx2, ry2)
                elif i == 2:
                    single_q1 = np.dot(rz1, ry1)
                    single_q2 = la.multi_dot([rx2, pauli_y, ry2])
                else:
                    single_q1 = np.dot(rz1, ry1)
                    single_q2 = la.multi_dot([pauli_x, rx2, ry2])

                # we place single qubit matrices at the corresponding locations in
                # the (2^n, 2^n) matrix
                full_q1 = place_unitary(single_q1, n, q1)
                full_q2 = place_unitary(single_q2, n, q2)

                # we place a cnot matrix at the qubits q1 and q2 in the full matrix
                cnot_q1q2 = place_cnot(n, q1, q2)

                # partial derivative of that particular cnot unit, size of (2^n, 2^n)
                der_cnot_unit = la.multi_dot([full_q2, full_q1, cnot_q1q2])
                # der_cnot_unit is multiplied by the matrix product of cnot units to the left
                # of it (if there are any) and to the right of it (if there are any)
                if cnot_index == 0:
                    der_cnot_matrix = np.dot(
                        self._cnot_right_collection[:, d : 2 * d],
                        der_cnot_unit,
                    )
                elif num_cnots - 1 == cnot_index:
                    der_cnot_matrix = np.dot(
                        der_cnot_unit,
                        self._cnot_left_collection[:, d * (num_cnots - 2) : d * (num_cnots - 1)],
                    )
                else:
                    der_cnot_matrix = la.multi_dot(
                        [
                            self._cnot_right_collection[
                                :, d * (cnot_index + 1) : d * (cnot_index + 2)
                            ],
                            der_cnot_unit,
                            self._cnot_left_collection[:, d * (cnot_index - 1) : d * cnot_index],
                        ]
                    )

                # the matrix corresponding to the full circuit partial derivative
                # is the partial derivative of the cnot part multiplied by the usual
                # rotation part
                der_circuit_matrix = np.dot(der_cnot_matrix, self._rotation_matrix)
                # we compute the partial derivative of the cost function
                der[i + theta_index] = -np.real(
                    np.trace(np.dot(der_circuit_matrix.conj().T, self._target_matrix))
                )

        # now we compute the partial derivatives in the rotation part
        # we start with 1 and kronecker product each qubit's rotations
        for i in range(3 * n):
            der_rotation_matrix = 1
            for q in range(n):
                theta_index = 4 * num_cnots + 3 * q
                rz0 = rz_matrix(thetas[0 + theta_index])
                ry1 = ry_matrix(thetas[1 + theta_index])
                rz2 = rz_matrix(thetas[2 + theta_index])
                # for the appropriate rotation gate that we are taking
                # the partial derivative of, we have to insert the
                # corresponding pauli matrix
                if i - 3 * q == 0:
                    rz0 = np.dot(pauli_z, rz0)
                elif i - 3 * q == 1:
                    ry1 = np.dot(pauli_y, ry1)
                elif i - 3 * q == 2:
                    rz2 = np.dot(pauli_z, rz2)
                der_rotation_matrix = np.kron(der_rotation_matrix, la.multi_dot([rz0, ry1, rz2]))

            # the matrix corresponding to the full circuit partial derivative
            # is the usual cnot part multiplied by the partial derivative of
            # the rotation part
            der_circuit_matrix = np.dot(self._cnot_matrix, der_rotation_matrix)
            # we compute the partial derivative of the cost function
            der[4 * num_cnots + i] = -np.real(
                np.trace(np.dot(der_circuit_matrix.conj().T, self._target_matrix))
            )

        return der
def affine_LK_tracker(img, frame, tmp, rect, pprev):
    p1, p2, p3, p4 = np.transpose(np.array(rect[0])), np.transpose(
        np.array(rect[1])), np.transpose(np.array(rect[2])), np.transpose(
            np.array(rect[3]))
    p = pprev
    norm = 5
    itr = 0

    for i in range(10):
        if norm >= 0.15:
            p_matrix = np.array([[1 + p[0], p[2], p[4]],
                                 [p[1], 1 + p[3], p[5]], [0, 0, 1]])
            # Step 1 - Getting the new ROI in current frame and warping template to it
            p1new, p2new, p3new, p4new = np.dot(p_matrix, p1)[0:2], np.dot(
                p_matrix, p2)[0:2], np.dot(p_matrix,
                                           p3)[0:2], np.dot(p_matrix, p4)[0:2]
            M = np.array([[1 + p[0], p[2], p[4]], [p[1], 1 + p[3], p[5]]],
                         dtype=np.float32)
            img_warp = cv2.warpAffine(img,
                                      M, (0, 0),
                                      flags=cv2.INTER_CUBIC +
                                      cv2.WARP_INVERSE_MAP)
            img_warp = img_warp[int(p1[1]):int(p4[1]), int(p1[0]):int(p4[0])]
            # Step 2 - Compute the error Image: Template - Warped image
            error_img = tmp - img_warp
            # Step 3 - Compute the gradient of the current frame
            x_grad = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
            y_grad = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
            x_grad = cv2.warpAffine(x_grad,
                                    M, (0, 0),
                                    flags=cv2.INTER_CUBIC +
                                    cv2.WARP_INVERSE_MAP)
            y_grad = cv2.warpAffine(y_grad,
                                    M, (0, 0),
                                    flags=cv2.INTER_CUBIC +
                                    cv2.WARP_INVERSE_MAP)
            x_grad = x_grad[int(p1[1]):int(p4[1]), int(p1[0]):int(p4[0])]
            y_grad = y_grad[int(p1[1]):int(p4[1]), int(p1[0]):int(p4[0])]
            gradient_map = []
            # Step 4 - Compute the Jacobian of the warp
            jacobian_map = []
            steepest_descent = []
            W = []
            sigma = 1.7034
            for i in range(x_grad.shape[0]):
                for j in range(x_grad.shape[1]):
                    steepest_descent.append(
                        np.dot(np.array([x_grad[i, j], y_grad[i, j]]),
                               np.array(jacobian(i, j))))
                    weight = (1 / sigma * math.sqrt(2 * np.pi)) * math.exp(
                        (-(math.sqrt((i - x_grad.shape[0] / 2)**2 +
                                     (j - x_grad.shape[1] / 2)**2))**2) /
                        (2 * (sigma**2)))
                    W.append(weight)
            jacobian_map = np.array(jacobian_map)
            gradient_map = np.array(gradient_map)
            # Step 5 - Compute Steepest descent
            steepest_descent = np.array(steepest_descent)
            # Huber Loss - Weighted Window Intermidiate step- Calculate diagonal weight matrix
            W = np.diag(W)
            # Step 6 - Compute the Hessian matrix
            H = multi_dot(
                [np.transpose(steepest_descent), W, steepest_descent])
            # Step 7 - Compute updated delta P
            delta_p = multi_dot([
                np.linalg.pinv(H),
                np.transpose(steepest_descent), W,
                error_img.flatten()
            ])
            # Step 8 - Compute Norm of delta P
            norm = np.linalg.norm(delta_p)
            # Step 9 - Update P matrix
            delta_p = np.dot(delta_p, 0.005)
            p = np.add(p, delta_p)
            itr = itr + 1
        else:
            break

    tracked_frame = cv2.rectangle(frame, (int(p1new[0]), int(p1new[1])),
                                  (int(p4new[0]), int(p4new[1])), (0, 0, 255),
                                  4)
    #print('Shape:', tracked_frame.shape)
    #cv2.imshow('tracked_frame', img)
    #cv2.waitKey(0)
    return p, tracked_frame
def handEye(M, N, number):
    for i in range(number):
        Y = multi_dot([M[i], X, inv(N[i])])
        print(Y)
Exemple #23
0
 def ov(vi, vj):
     return multi_dot([vi, G, vj])
Exemple #24
0
    def parse_input(self, X):
        """Fast ML Graph Kernel.

        See supplementary material :cite:`kondor2016multiscale`, algorithm 1.

        Parameters
        ----------
        X : iterable
            For the input to pass the test, we must have:
            Each element must be an iterable with at most three features and at
            least one. The first that is obligatory is a valid graph structure
            (adjacency matrix or edge_dictionary) while the second is
            node_labels and the third edge_labels (that correspond to the given
            graph format). A valid input also consists of graph type objects.

        Returns
        -------
        out : list
            A list of tuples with S matrices inverses
            and their 4th-root determinants.

        """
        if not isinstance(X, collections.Iterable):
            raise TypeError('input must be an iterable\n')
        else:
            ng = 0
            out = list()
            data = dict()
            neighborhoods = dict()
            for (idx, x) in enumerate(iter(X)):
                is_iter = False
                if isinstance(x, collections.Iterable):
                    is_iter, x = True, list(x)
                if is_iter and len(x) in [0, 2, 3]:
                    if len(x) == 0:
                        warnings.warn('Ignoring empty element ' +
                                      'on index: ' + str(idx))
                        continue
                    else:
                        x = Graph(x[0], x[1], {}, self._graph_format)
                elif type(x) is not Graph:
                    x.desired_format(self._graph_format)
                else:
                    raise TypeError('each element of X must be either a '
                                    'graph or an iterable with at least 1 '
                                    'and at most 3 elements\n')
                phi_d = x.get_labels()
                A = x.get_adjacency_matrix()
                try:
                    phi = np.array([list(phi_d[i]) for i in range(A.shape[0])])
                except TypeError:
                    raise TypeError('Features must be iterable and castable '
                                    'in total to a numpy array.')

                Lap = laplacian(A).astype(float)
                _increment_diagonal_(Lap, self.heta)
                data[ng] = {0: A, 1: phi, 2: inv(Lap)}
                neighborhoods[ng] = x
                ng += 1

            if ng == 0:
                raise ValueError('parsed input is empty')

            # Define a function for calculating the S's of subgraphs of each iteration
            def calculate_C(k, j, l):
                if type(neighborhoods[k]) is Graph:
                    neighborhoods[k] = neighborhoods[k].produce_neighborhoods(
                        r=self.L, sort_neighbors=False)

                indexes = neighborhoods[k][l][j]
                L = laplacian(data[k][0][indexes, :][:, indexes]).astype(float)
                _increment_diagonal_(L, self.heta)
                U = data[k][1][indexes, :]
                S = multi_dot((U.T, inv(L), U))
                _increment_diagonal_(S, self.gamma)

                return (inv(S), np.sum(np.log(np.real(eigvals(S)))))

            if self._method_calling == 1:
                V = [(k, j) for k in range(ng)
                     for j in range(data[k][0].shape[0])]

                ns = min(len(V), self.n_samples)

                self.random_state_.shuffle(V)
                vs = V[:ns]
                phi_k = np.array([data[k][1][j, :] for (k, j) in vs])

                # w the eigen vectors, v the eigenvalues
                K = phi_k.dot(phi_k.T)

                # Calculate eigenvalues
                v, w = eig(K)
                v, w = np.real(v), np.real(w.T)

                # keep only the positive
                vpos = np.argpartition(v, -self.P)[-self.P:]
                vpos = vpos[np.where(v[vpos] > positive_eigenvalue_limit)]

                # ksi.shape = (k, Ns) * (Ns, P)
                ksi = w[vpos].dot(phi_k).T / np.sqrt(v[vpos])
                for j in range(ng):
                    # (n_samples, k) * (k, P)
                    data[j][1] = data[j][1].dot(ksi)
                self._data_level = {0: ksi}
                for l in range(1, self.L + 1):
                    # Take random samples from all the vertices of all graphs
                    self.random_state_.shuffle(V)
                    vs = V[:ns]

                    # Compute the reference subsampled Gram matrix
                    K_proj = {
                        k: np.zeros(shape=(data[k][0].shape[0], ns))
                        for k in range(ng)
                    }
                    K, C = np.zeros(shape=(len(vs), len(vs))), dict()
                    for (m, (k, j)) in enumerate(vs):
                        C[m] = calculate_C(k, j, l)
                        K_proj[k][j, m] = K[m, m] = self.pairwise_operation(
                            C[m], C[m])
                        for (s, (k2, j2)) in enumerate(vs):
                            if s < m:
                                K[s, m] = K[m, s] \
                                        = K_proj[k2][j2, m] \
                                        = K_proj[k][j, s] \
                                        = self.pairwise_operation(C[s], C[m])
                            else:
                                break

                    # Compute the kernels of the relations of the reference to everything else
                    for (k, j) in V[ns:]:
                        for (m, _) in enumerate(vs):
                            K_proj[k][j, m] = self.pairwise_operation(
                                C[m], calculate_C(k, j, l))

                    # w the eigen vectors, v the eigenvalues
                    v, w = eig(K)
                    v, w = np.real(v), np.real(w.T)

                    # keep only the positive
                    vpos = np.argpartition(v, -self.P)[-self.P:]
                    vpos = vpos[np.where(v[vpos] > positive_eigenvalue_limit)]

                    # Q shape=(k, P)
                    Q = w[vpos].T / np.sqrt(v[vpos])
                    for j in range(ng):
                        # (n, ns) * (ns, P)
                        data[j][1] = K_proj[j].dot(Q)
                    self._data_level[l] = (C, Q)

            elif self._method_calling == 3:
                ksi = self._data_level[0]
                for j in range(ng):
                    # (n, k) * (k, P)
                    data[j][1] = data[j][1].dot(ksi)

                for l in range(1, self.L + 1):
                    C, Q = self._data_level[l]
                    for j in range(ng):
                        K_proj = np.zeros(shape=(data[j][0].shape[0], len(C)))
                        for n in range(data[j][0].shape[0]):
                            for m in range(len(C)):
                                K_proj[n, m] = self.pairwise_operation(
                                    C[m], calculate_C(j, n, l))
                        data[j][1] = K_proj.dot(Q)

            # Apply the final calculation of S.
            for k in range(ng):
                S = multi_dot((data[k][1].T, data[k][2], data[k][1]))
                _increment_diagonal_(S, self.gamma)
                out.append((inv(S), np.sum(np.log(np.real(eigvals(S))))))

            return out
Exemple #25
0
 def guess_hessian(self, coords):
     """ Build the guess Hessian, consisting of a diagonal matrix 
     in the primitive space and changed to the basis of DLCs. """
     Hprim = self.Prims.guess_hessian(coords)
     return multi_dot([self.Vecs.T, Hprim, self.Vecs])
Exemple #26
0
def HSIC_Test(Kx, Ky, Kzx, Kzy, pars):
    # Hilbert Schmidt Independence Criterion (HSIC) test using semi-paired data
    # Inputs:
    #       Kx - kernel matrix on x (NxN, the first np x np block contains paired data)
    #       Ky - kernel matrix on y (MxM, the first np x np block contains paired data)
    #       Kzx - kernel matrix on covariate z (for x, empty if not exist)
    #       Kzy - kernel matrix on covariate z (for y, empty if not exist)
    #       pars - hyperparameters
    #           .np - number of paired data
    #           .rx - reduced dimension of x, default pars.np
    #           .ry - reduced dimension of y, default pars.np
    #           .stId - remove the top (stId) eigenvalues (for genotype data), defaut 0
    #           .T_BS - bootstrap sample size, default 10000
    #           .uv - 'u' or 'v' statistics, default 'u'
    #           .test - compute p-values if true, default true
    # Outputs:
    #       p_val0 - p value of the original HSIC using only paired data
    #       p_val - p value of our Semi-paired test (SAT), only improve null distribution
    #       p_valSemi - p value of our SAT, improve both test statistics and null distribution
    #       Sta - test statistic of the original HSIC using only paired data
    #       StaSemi - test statistic of our SAT

    Tx = len(Kx)  # The sample size
    Ty = len(Ky)
    rx = pars['rx']
    ry = pars['ry']
    Tn = pars['np']
    stId = pars['stId']

    # Boostrap parameters
    T_BS = pars.get('T_BS', 10000)
    Thresh = 1e-8

    # Original HSIC
    H = np.eye(Tn) - np.ones((Tn, Tn)) / Tn
    Hzx = np.eye(Tx) - np.ones((Tx, Tx)) / Tx

    if Kzx.size != 0:
        Kzx = multi_dot([Hzx, Kzx, Hzx])
        epsilon = 1e-5
        Rx = epsilon * inv((Kzx + epsilon * np.eye(Tx)))
        Kx = multi_dot([Rx, Kx, Rx])

    if Kzy.size != 0:
        Kzy = multi_dot([Hzy, Kzy, Hzy])
        epsilon = 1e-5
        Ry = epsilon * inv((Kzy + epsilon * np.eye(Ty)))
        Ky = multi_dot([Ry, Ky, Ry])

    Kxl = Kx[0:Tn, 0:Tn].copy()
    Kxlc = multi_dot([H, Kxl, H])

    # remove top eigs of Y (SNPs)
    Hy = np.eye(Ty) - np.ones((Ty, Ty)) / Ty
    KyC = multi_dot([Hy, Ky, Hy])
    uy1, dy1 = getEigen(KyC)

    reg = 1e-5

    # remove top eigenvalues
    KylP = multi_dot([\
             Ky[:Tn,:],\
             Hy,\
             uy1[:,stId:matrix_rank(KyC)],\
             inv(dy1[stId:matrix_rank(KyC),stId:matrix_rank(KyC)]+\
               reg*np.eye(matrix_rank(KyC)-stId)),\
             np.transpose(uy1[:,stId:matrix_rank(KyC)]),\
             Hy,\
             Ky[:,:Tn]])

    if pars['uv'] == 'v':
        KylPC = multi_dot([H, KylP, H])
        Sta = np.trace(np.dot(Kxlc, KylPC)) / Tn ^ 2
    elif pars['uv'] == 'u':
        onev = np.ones((Tn, 1))
        Kxl_zero = Kxl
        Kxl_zero[np.eye(Tn).astype(np.bool)] = 0
        Kyl_zero = KylP
        KylPC = multi_dot([H, KylP, H])
        Kyl_zero[np.eye(Tn).astype(np.bool)] = 0
        Sta1 = np.trace(np.dot(Kxl_zero, Kyl_zero)) / Tn / (Tn - 3)
        Sta2 = multi_dot([
            np.transpose(onev), Kxl_zero, onev,
            np.transpose(onev), Kyl_zero, onev
        ]) / Tn / (Tn - 1) / (Tn - 2) / (Tn - 3)
        Sta3 = multi_dot([np.transpose(onev), Kxl_zero, Kyl_zero, onev
                          ]) / Tn / (Tn - 2) / (Tn - 3)
        Sta = Sta1 + Sta2 - 2 * Sta3

    if pars['test'] == 1:
        p_val0 = cal_pval(Sta, Kxlc, KylPC, Tn, T_BS, Tn, Tn, Thresh, stId,
                          pars['uv'])
    else:
        p_val0 = None

    if Tn == Tx and Tn == Ty:
        p_val = p_val0
        p_valSemi = p_val0
        StaSemi = Sta
        return p_val0, p_val, p_valSemi, Sta, StaSemi

    Hx = np.eye(Tx) - np.ones((Tx, Tx)) / Tx
    KxC = multi_dot([Hx, Kx, Hx])
    ux1, dx1 = getEigen(KxC)

    # original HSIC + modified null distr
    if pars['test'] == 1:
        p_val = cal_pval(Sta, KxC, KyC, Tn, T_BS, Tx, Ty, Thresh, stId,
                         pars['uv'])
    else:
        p_val = None

    if rx == Tx and ry == Ty:
        p_valSemi = p_val
        StaSemi = Sta
        return p_val0, p_val, p_valSemi, Sta, StaSemi

    # modified HSIC + modified null distr
    reg = 1e-5
    KxS = multi_dot([Kx[:Tn,:],
                     Hx,\
                     right_divide(ux1[:,:rx], (dx1[:rx,:rx]+reg*np.eye(rx))),\
                     np.transpose(ux1[:,:rx]),\
                     Hx,\
                     Kx[:,:Tn]])
    KyS = multi_dot([
        Ky[:Tn, :], Hy,
        right_divide(uy1[:, stId:ry],
                     (dy1[stId:ry, stId:ry] + reg * np.eye(ry - stId))),
        uy1[:, stId:ry].transpose(), Hy, Ky[:, :Tn]
    ])
    #print(KxS)
    #print(KyS)

    if pars['uv'] == 'v':
        KxSC = multi_dot([H, KxS, H])
        KySC = multi_dot([H, KyS, H])
        StaSemi = np.trace(np.dot(KxSC, KySC)) / (Tn ^ 2)
    elif pars['uv'] == 'u':
        onev = np.ones((Tn, 1))
        KxS_zero = KxS
        KxS_zero[np.eye(Tn).astype(np.bool)] = 0
        KyS_zero = KyS
        KyS_zero[np.eye(Tn).astype(np.bool)] = 0
        Sta1 = np.trace(np.dot(KxS_zero, KyS_zero)) / Tn / (Tn - 3)
        Sta2 = multi_dot([
            np.transpose(onev), KxS_zero, onev,
            np.transpose(onev), KyS_zero, onev
        ]) / Tn / (Tn - 1) / (Tn - 2) / (Tn - 3)
        Sta3 = multi_dot([np.transpose(onev), KxS_zero, KyS_zero, onev
                          ]) / Tn / (Tn - 2) / (Tn - 3)
        #print(Sta1)
        #print(Sta2)
        #print(Sta3)
        StaSemi = Sta1 + Sta2 - 2 * Sta3

    if pars['test'] == 1:
        p_valSemi = cal_pval(StaSemi, KxC, KyC, Tn, T_BS, rx, ry, Thresh, stId,
                             pars['uv'])
    else:
        p_valSemi = None
    return p_val0, p_val, p_valSemi, Sta, StaSemi
Exemple #27
0
def get_delta_prime_rs_p_rfo(alpha, X, G, H, IC, verbose=0):
    """
    Return the restricted-step rational functional optimization
    step, given a particular value of alpha. The step is given by:
    1) Solving the generalized eigenvalue problem
    [[0 G]  = lambda * [[1 0] * vec ,
     [G H]]             [0 S]]
       where the LHS matrix is called the augmented Hessian,
       and S is alpha times the identity (starting value 1.0).
    2) Dividing vec through by the 0th element, and keeping the rest
    This function also calculates the derivative of the norm of the step
    with respect to alpha, which allows trust_step() to rapidly find
    the RS-RFO step that satisfies a desired step length.

    Currently does not work with constraints, and gives equivalent performance
    to the trust radius method.

    Parameters
    ----------
    alpha : float
        Multiple of the identity in the S-matrix
    X : np.ndarray
        Flat array of Cartesian coordinates in atomic units
    G : np.ndarray
        Flat array containing internal gradient
    H : np.ndarray
        Square array containing internal Hessian
    IC : InternalCoordinates
        Object describing the internal coordinate system
    verbose : int
        Print diagnostic messages

    Returns
    -------
    dy : np.ndarray
        The internal coordinate step
    expect : float
        Expected change of the objective function
    dy_prime : float
        Derivative of the internal coordinate step size w/r.t. v
    """
    if IC.haveConstraints():
        raise RuntimeError("Rational function optimization does not support constraints")
    # verbose = 2
    if verbose >= 4:
        logger.info("        === RS-P-RFO method with alpha = %.5f ===\n" % alpha)

    # Sorted eigenvalues and corresponding eigenvectors of the Hessian
    Hvals, Hvecs = sorted_eigh(H, asc=True)

    # Projection of gradient along the Hessian eigenvectors
    Gproj = np.dot(Hvecs.T, G)

    # Indices of the transition vector (which forms the small RFO partition) and the other vectors
    tv = 0
    ot = np.array([i for i in range(H.shape[0]) if i != tv])

    # The P-RFO matrices follow the convention of Bofill (1998)
    # with the "extra" row in the upper left.
    # Form the small P-RFO matrix, which is a 2x2 matrix
    prfo_tv = np.array([[0, Gproj[tv]], [Gproj[tv], Hvals[tv]]])
    # Form the large P-RFO matrix, which is the same size as H itself
    prfo_ot = np.zeros_like(H)
    # Fill matrix (except top left) with the non-'tv' eigenvalues
    prfo_ot[1:, 1:] = np.diag(Hvals[ot])
    # Fill the top row and left column with the non-'tv' gradient components
    prfo_ot[0, 1:] = Gproj[ot]
    prfo_ot[1:, 0] = Gproj[ot]

    # Solve the generalized eigenvector problems
    tv_vals, tv_vecs = rfo_gen_evp(prfo_tv, alpha)
    ot_vals, ot_vecs = rfo_gen_evp(prfo_ot, alpha)

    ## Form the P-RFO step.
    dy_tv = -Gproj[tv]*Hvecs[:,tv]/(Hvals[tv]-tv_vals[-1]*alpha)
    denoms = np.zeros_like(dy_tv)
    dy_coeffs = np.zeros_like(dy_tv)
    dy_coeffs[tv] = -Gproj[tv]/(Hvals[tv]-tv_vals[-1]*alpha)
    denoms[tv] = Hvals[tv]-tv_vals[-1]*alpha
    # Compute transition vector contribution to |dy|^2/d(alpha)
    dy2_prime_tv = 2 * (tv_vals[-1]/(1+alpha*np.dot(dy_tv,dy_tv))) * (Gproj[tv]**2/(Hvals[tv]-tv_vals[-1]*alpha)**3)
    # Now for the other vectors
    dy_ot = np.zeros_like(dy_tv)
    dy2_prime_ot = 0.0
    for i in ot:
        denom = Hvals[i]-ot_vals[0]*alpha
        denoms[i] = denom
        # Numerical instabilities can occur when the shift is very close to a pole,
        # so we exclude these components.
        if np.abs(denom) > 1e-5:
            dy_ot -= Gproj[i]*Hvecs[:,i]/denom
            dy_coeffs[i] = -Gproj[i]/denom
            dy2_prime_ot += Gproj[i]**2/denom**3
    dy2_prime_ot *= 2 * (ot_vals[0]/(1+alpha*np.dot(dy_ot,dy_ot)))
    # Add the transition vector and other vector contributions together
    dy = dy_tv + dy_ot
    dy2_prime = dy2_prime_tv + dy2_prime_ot
    # Derivative of the norm of the step w/r.t. alpha
    dy_prime = dy2_prime/(2*np.linalg.norm(dy))
    # For some reason, this formula from the paper suffers from some numerical problems
    # expect = (tv_vals[-1]/tv_vecs[0,-1]**2 + ot_vals[0]/ot_vecs[0,0]**2) / 2
    # Use the quadratic approximation to get expected change in the energy
    expect = flat(0.5*multi_dot([row(dy),H,col(dy)]))[0] + np.dot(dy,G)

    if verbose >= 5:
        logger.info("        Largest / smallest eigvals of small / large P-RFO matrix: % .5f % .5f\n" % (tv_vals[-1], ot_vals[0]))
        logger.info("        Small P-RFO matrix:\n        ")
        pmat2d(prfo_tv, precision=5, format='f')
        logger.info("        Eigenvalues of small P-RFO matrix:\n        ")
        pvec1d(tv_vals, precision=5, format='f')
        logger.info("        Large P-RFO matrix:\n        ")
        pmat2d(prfo_ot, precision=5, format='f')
        logger.info("        Eigenvalues of large P-RFO matrix:\n        ")
        pvec1d(ot_vals, precision=5, format='f')
        logger.info("        l_max*alpha, l_min*alpha = %.5f %.5f\n" % (tv_vals[-1]*alpha, ot_vals[0]*alpha))
        logger.info("        Numerator   of Gproj[i]/(h[i]-l*a) along each mode:\n        ")
        pvec1d(Gproj)
        logger.info("        Denominator of Gproj[i]/(h[i]-l*a) along each mode:\n        ")
        pvec1d(denoms)
        logger.info("        Coefficients of P-RFO step along each mode:\n        ")
        pvec1d(dy_coeffs)
        logger.info("        Step obtained from P-RFO method:\n        ")
        pvec1d(dy)
    elif verbose >= 4:
        logger.info("        Largest / smallest eigvals of small / large P-RFO matrix: % .5f % .5f\n" % (tv_vals[-1], ot_vals[0]))
        logger.info("        l_max*alpha(TS), l_min*alpha(min) = %.5f %.5f\n" % (tv_vals[-1]*alpha, ot_vals[0]*alpha))
        logger.info("        Coefficients of P-RFO step along normal modes:\n")
        printIdxs = list(np.argsort(np.abs(dy_coeffs))[-4:])
        if 0 not in printIdxs: printIdxs.append(0)
        for i in sorted(printIdxs):
            logger.info("          dy[%3i] = % .6f\n" % (i, dy_coeffs[i]))
        # pvec1d(dy_coeffs, precision=3, format='f')

    return dy, expect, dy_prime
fin = open(in_filename1, 'r')
data = np.loadtxt(fin)
padding1 = np.full((1000, 1), 1)
padding2 = np.full((3000, 1), 1)
fin.close()
fin = open(in_filename2, 'r')
test = np.loadtxt(fin)
data = np.append(padding1, data, axis=1)
test = np.append(padding2, test, axis=1)
data = Qtransform(data, 10)
test = Qtransform(test, 10)
x = data[0:1000, 0:101]
y = data[0:1000, 101:102]
xt = x.transpose()
xr = np.dot(xt, x)
xin = inv(xr)
Wlin = multi_dot([xin, xt, y])
xtest = test[0:3000, 0:101]
ytest = test[0:3000, 101:102]
reg1 = np.dot(x, Wlin)
reg2 = np.dot(xtest, Wlin)
err1 = 0
err2 = 0
for i in range(1000):
    if reg1[i][0] * y[i][0] < 0:
        err1 = err1 + 1
for i in range(3000):
    if reg2[i][0] * ytest[i][0] < 0:
        err2 = err2 + 1
print(abs(err1 - err2 / 3) / 1000)
fin.close()
Exemple #29
0
def get_delta_prime_rfo(alpha, X, G, H, IC, verbose=0):
    """
    Return the restricted-step rational functional optimization
    step, given a particular value of alpha. The step is given by:
    1) Solving the generalized eigenvalue problem
    [[0 G]  = lambda * [[1 0] * vec ,
     [G H]]             [0 S]]
       where the LHS matrix is called the augmented Hessian,
       and S is alpha times the identity (starting value 1.0).
    2) Dividing vec through by the 0th element, and keeping the rest
    This function also calculates the derivative of the norm of the step
    with respect to alpha, which allows trust_step() to rapidly find
    the RS-RFO step that satisfies a desired step length.

    Currently does not work with constraints, and gives equivalent performance
    to the trust radius method.

    Parameters
    ----------
    alpha : float
        Multiple of the identity in the S-matrix
    X : np.ndarray
        Flat array of Cartesian coordinates in atomic units
    G : np.ndarray
        Flat array containing internal gradient
    H : np.ndarray
        Square array containing internal Hessian
    IC : InternalCoordinates
        Object describing the internal coordinate system
    verbose : int
        Print diagnostic messages

    Returns
    -------
    dy : np.ndarray
        The internal coordinate step
    expect : float
        Expected change of the objective function
    dy_prime : float
        Derivative of the internal coordinate step size w/r.t. v
    """
    try:
        import scipy
    except ImportError:
        raise ImportError("RFO optimization requires scipy package. If this becomes important in the future, scipy will become a required dependency.")
    if IC.haveConstraints():
        raise RuntimeError("Still need to implement RFO with constraints")
    S = alpha*np.eye(len(H))
    # Augmented Hessian matrix
    AH = np.zeros((H.shape[0]+1, H.shape[1]+1), dtype=float)
    AH[1:, 1:] = H
    AH[0, 1:] = G
    AH[1:, 0] = G
    B = np.zeros_like(AH)
    B[0,0] = 1.0
    B[1:,1:] = S
    # Solve the generalized eigenvalue problem
    AHeig, AHvec = scipy.linalg.eigh(AH, b=B)
    lmin = AHeig[0]
    # logger.info("AH eigenvalues: %.5e %.5e %.5e ... %.5e %.5e %.5e" % (AHeig[0],AHeig[1],AHeig[2],AHeig[-3],AHeig[-2],AHeig[-1]))
    vmin = np.array(AHvec[:, 0]).flatten()
    dy = (vmin / vmin[0])[1:]
    nu = alpha*lmin
    # Now get eigenvectors of the Hessian
    Heig, Hvec = sorted_eigh(H, asc=True)
    Hvec = np.array(Hvec)
    dyprime2 = 0
    dy2 = 0
    for i in range(H.shape[0]):
        dyprime2 += np.dot(Hvec[:,i].T,G)**2/(Heig[i]-nu)**3
        dy2 += np.dot(Hvec[:,i].T,G)**2/(Heig[i]-nu)**2
    dyprime2 *= (2*lmin)/(1+alpha*np.dot(dy,dy))
    expect = lmin/2*(1+multi_dot([row(dy),S,col(dy)]))[0]
    dyprime1 = dyprime2 / (2*np.sqrt(dy2))
    return dy, expect, dyprime1
Exemple #30
0
def build_Hk_5(QE_xml_data_file,shift,shift_type,Hk_space,Hk_outfile,nbnds_norm=0,nbnds_in=0):
    """
    returns Hk:
    build_Hk_2: includes all the bands that lay under the 'shift' energy.
    build_Hk_3: Optionally one can inclue a fixed number of bands with 'nbnds_in';
                this capability is similar to WanT's 'atmproj_nbnd'.
    shift_type: 0 = regular shifting. 1 = new shifting

    build_Hk_4: -a bug for nonortho shifting is corrected: Sks was needed for that case.
                -changed the name of the output variable from Hks to Hk.
    build_Hk_5: reads nawf,nkpnts,nspin,shift,eigsmat, from QE_xml_data_file
    """
    nproc = 1

    if not os.path.isfile(QE_xml_data_file):
        sys.exit('File not found: {0:s}'.format(QE_xml_data_file))
    data      = np.load(QE_xml_data_file)
    nawf      = int(data['nawf'])
    nkpnts    = int(data['nkpnts'])
    nspin     = int(data['nspin'])
    eigsmat   = data['eigsmat']
    Sks       = data['Sk']
    U         = data['U']


    if Hk_space.lower()=='ortho':
       del Sks 
    elif Hk_space.lower()=='nonortho':
       if len(Sks.shape) != 3: sys.exit('Need Sks[nawf,nawf,nkpnts]  for nonortho calculations')
    else:
       sys.exit('wrong Hk_space option. Only ortho and nonortho are accepted')

    tic = time.time()
    Hks = np.zeros((nawf,nawf,nkpnts,nspin),dtype=complex)
    for ispin in range(nspin):
        for ik in range(nkpnts):
            my_eigs=eigsmat[:,ik,ispin]
            E = np.diag(my_eigs)
            UU    = U[:,:,ik,ispin] #transpose of U. Now the columns of UU are the eigenvector of length nawf
            if nbnds_norm > 0:
                norms = 1/np.sqrt(np.real(np.sum(np.conj(UU)*UU,axis=0)))
                UU[:,:nbnds_norm] = UU[:,:nbnds_norm]*norms[:nbnds_norm]
            kappa = shift
            if nbnds_in == 0:
               iselect   = np.where(my_eigs <= shift)[0]
            elif nbnds_in > 0:
               iselect   = range(nbnds_in)
            else:
               sys.exit('build_Hk_4: wrong nbnd variable')

            ac    = UU[:,iselect]
            ee1   = E[np.ix_(iselect,iselect)]

            if shift_type ==0:
                Hks_aux = ac.dot(ee1).dot(np.conj(ac).T) + kappa*( -ac.dot(np.conj(ac).T))
            elif shift_type==1:
                aux_p=la.inv(np.dot(np.conj(ac).T,ac))
                Hks_aux = ac.dot(ee1).dot(np.conj(ac).T) + kappa*( -ac.dot(aux_p).dot(np.conj(ac).T))
            else:
                sys.exit('shift_type not recognized')


                Hks_aux = np.triu(Hks_aux,1)+np.diag(np.diag(Hks_aux))+np.conj(np.triu(Hks_aux,1)).T

            if Hk_space.lower()=='ortho':
                Hks[:,:,ik,ispin] = Hks_aux  + kappa*np.identity(nawf)
            elif Hk_space.lower()=='nonortho':
                Sk_half = sla.fractional_matrix_power(Sks[:,:,ik],0.5)
                if 'multi_dot' in dir (la):
                    Hks[:,:,ik,ispin] =la.multi_dot([Sk_half,Hks_aux,Sk_half])+kappa*Sks[:,:,ik]
                else:
                    Hks[:,:,ik,ispin] =np.dot(np.dot(Sk_half,Hks_aux),Sk_half)+kappa*Sks[:,:,ik]

            else:
                sys.exit('wrong Hk_space option. Only ortho and nonortho are accepted')


    
    np.savez(Hk_outfile,Hk=Hks,nbnds_norm=nbnds_norm,nbnds_in=nbnds_in,shift_type=shift_type,shift=shift)
            
    toc = time.time()
    hours, rem = divmod(toc-tic, 3600)
    minutes, seconds = divmod(rem, 60)
    print("Parallel calculation of H[k] with {0:d} processors".format(nproc))
    print("Elapsed time {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
    return Hks
    def eval_acc_eq(self):
        config = self.config
        t = self.t

        a0 = self.Mbar_vbs_chassis_jcs_input_bearing[:,2:3]
        a1 = a0.T
        a2 = self.P_vbs_chassis
        a3 = A(a2).T
        a4 = self.Pd_rbs_input_shaft
        a5 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]
        a6 = B(a4,a5)
        a7 = a5.T
        a8 = self.P_rbs_input_shaft
        a9 = A(a8).T
        a10 = self.Pd_vbs_chassis
        a11 = B(a10,a0)
        a12 = a4.T
        a13 = B(a8,a5).T
        a14 = B(a2,a0)
        a15 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]
        a16 = B(a4,a15)
        a17 = a15.T
        a18 = B(a8,a15).T
        a19 = self.ubar_rbs_input_shaft_jcs_input_bearing
        a20 = self.ubar_vbs_chassis_jcs_input_bearing
        a21 = (multi_dot([B(a4,a19),a4]) + -1*multi_dot([B(a10,a20),a10]))
        a22 = (self.Rd_rbs_input_shaft + -1*self.Rd_vbs_chassis + multi_dot([B(a8,a19),a4]) + -1*multi_dot([B(a2,a20),a10]))
        a23 = (self.R_rbs_input_shaft.T + -1*self.R_vbs_chassis.T + multi_dot([a19.T,a9]) + -1*multi_dot([a20.T,a3]))
        a24 = self.Mbar_vbs_chassis_jcs_input_bearing[:,0:1]
        a25 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]
        a26 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]
        a27 = self.Pd_rbs_connect_shaft
        a28 = self.Mbar_rbs_input_shaft_jcs_input_connect[:,0:1]
        a29 = self.Mbar_rbs_connect_shaft_jcs_input_connect[:,0:1]
        a30 = self.P_rbs_connect_shaft
        a31 = A(a30).T
        a32 = self.Pd_rbs_output_shaft
        a33 = self.Mbar_rbs_connect_shaft_jcs_output_connect[:,0:1]
        a34 = self.Mbar_rbs_output_shaft_jcs_output_connect[:,0:1]
        a35 = self.P_rbs_output_shaft
        a36 = A(a35).T
        a37 = a32.T
        a38 = self.Mbar_rbs_output_shaft_jcs_output_bearing[:,0:1]
        a39 = self.Mbar_vbs_chassis_jcs_output_bearing[:,2:3]
        a40 = B(a10,a39)
        a41 = a39.T
        a42 = B(a2,a39)
        a43 = self.Mbar_rbs_output_shaft_jcs_output_bearing[:,1:2]

        self.acc_eq_blocks = ((multi_dot([a1,a3,a6,a4]) + multi_dot([a7,a9,a11,a10]) + 2*multi_dot([a12,a13,a14,a10])),
        (multi_dot([a1,a3,a16,a4]) + multi_dot([a17,a9,a11,a10]) + 2*multi_dot([a12,a18,a14,a10])),
        (multi_dot([a7,a9,a21]) + 2*multi_dot([a12,a13,a22]) + multi_dot([a23,a6,a4])),
        (multi_dot([a17,a9,a21]) + 2*multi_dot([a12,a18,a22]) + multi_dot([a23,a16,a4])),
        (-1*derivative(config.UF_mcs_hand_wheel, t, 0.1, 2)*np.eye(1, dtype=np.float64) + multi_dot([a24.T,a3,(cos(config.UF_mcs_hand_wheel(t))*B(a4,a25) + -1*sin(config.UF_mcs_hand_wheel(t))*B(a4,a26)),a4]) + multi_dot([(cos(config.UF_mcs_hand_wheel(t))*multi_dot([a25.T,a9]) + -1*sin(config.UF_mcs_hand_wheel(t))*multi_dot([a26.T,a9])),B(a10,a24),a10]) + 2*multi_dot([(cos(config.UF_mcs_hand_wheel(t))*multi_dot([a12,B(a8,a25).T]) + -1*sin(config.UF_mcs_hand_wheel(t))*multi_dot([a12,B(a8,a26).T])),B(a2,a24),a10])),
        (multi_dot([B(a4,self.ubar_rbs_input_shaft_jcs_input_connect),a4]) + -1*multi_dot([B(a27,self.ubar_rbs_connect_shaft_jcs_input_connect),a27])),
        (multi_dot([a28.T,a9,B(a27,a29),a27]) + multi_dot([a29.T,a31,B(a4,a28),a4]) + 2*multi_dot([a12,B(a8,a28).T,B(a30,a29),a27])),
        (multi_dot([B(a32,self.ubar_rbs_output_shaft_jcs_output_connect),a32]) + -1*multi_dot([B(a27,self.ubar_rbs_connect_shaft_jcs_output_connect),a27])),
        (multi_dot([a33.T,a31,B(a32,a34),a32]) + multi_dot([a34.T,a36,B(a27,a33),a27]) + 2*multi_dot([a37,B(a35,a34).T,B(a30,a33),a27])),
        (multi_dot([B(a32,self.ubar_rbs_output_shaft_jcs_output_bearing),a32]) + -1*multi_dot([B(a10,self.ubar_vbs_chassis_jcs_output_bearing),a10])),
        (multi_dot([a38.T,a36,a40,a10]) + multi_dot([a41,a3,B(a32,a38),a32]) + 2*multi_dot([a37,B(a35,a38).T,a42,a10])),
        (multi_dot([a43.T,a36,a40,a10]) + multi_dot([a41,a3,B(a32,a43),a32]) + 2*multi_dot([a37,B(a35,a43).T,a42,a10])),
        2*multi_dot([a12,a4]),
        2*multi_dot([a27.T,a27]),
        2*multi_dot([a37,a32]),)
    def eval_reactions_eq(self):
        config  = self.config
        t = self.t

        Q_rbs_input_shaft_jcs_input_bearing = -1*multi_dot([np.bmat([[np.zeros((1,3),dtype=np.float64).T,np.zeros((1,3),dtype=np.float64).T,multi_dot([A(self.P_rbs_input_shaft),self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]]),multi_dot([A(self.P_rbs_input_shaft),self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]])],[multi_dot([B(self.P_rbs_input_shaft,self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]).T,A(self.P_vbs_chassis),self.Mbar_vbs_chassis_jcs_input_bearing[:,2:3]]),multi_dot([B(self.P_rbs_input_shaft,self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]).T,A(self.P_vbs_chassis),self.Mbar_vbs_chassis_jcs_input_bearing[:,2:3]]),(multi_dot([B(self.P_rbs_input_shaft,self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]).T,(-1*self.R_vbs_chassis + multi_dot([A(self.P_rbs_input_shaft),self.ubar_rbs_input_shaft_jcs_input_bearing]) + -1*multi_dot([A(self.P_vbs_chassis),self.ubar_vbs_chassis_jcs_input_bearing]) + self.R_rbs_input_shaft)]) + multi_dot([B(self.P_rbs_input_shaft,self.ubar_rbs_input_shaft_jcs_input_bearing).T,A(self.P_rbs_input_shaft),self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]])),(multi_dot([B(self.P_rbs_input_shaft,self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]).T,(-1*self.R_vbs_chassis + multi_dot([A(self.P_rbs_input_shaft),self.ubar_rbs_input_shaft_jcs_input_bearing]) + -1*multi_dot([A(self.P_vbs_chassis),self.ubar_vbs_chassis_jcs_input_bearing]) + self.R_rbs_input_shaft)]) + multi_dot([B(self.P_rbs_input_shaft,self.ubar_rbs_input_shaft_jcs_input_bearing).T,A(self.P_rbs_input_shaft),self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]]))]]),self.L_jcs_input_bearing])
        self.F_rbs_input_shaft_jcs_input_bearing = Q_rbs_input_shaft_jcs_input_bearing[0:3,0:1]
        Te_rbs_input_shaft_jcs_input_bearing = Q_rbs_input_shaft_jcs_input_bearing[3:7,0:1]
        self.T_rbs_input_shaft_jcs_input_bearing = (-1*multi_dot([skew(multi_dot([A(self.P_rbs_input_shaft),self.ubar_rbs_input_shaft_jcs_input_bearing])),self.F_rbs_input_shaft_jcs_input_bearing]) + 0.5*multi_dot([E(self.P_rbs_input_shaft),Te_rbs_input_shaft_jcs_input_bearing]))
        Q_rbs_input_shaft_mcs_hand_wheel = -1*multi_dot([np.bmat([[np.zeros((1,3),dtype=np.float64).T],[multi_dot([(-1*sin(config.UF_mcs_hand_wheel(t))*B(self.P_rbs_input_shaft,self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1]).T + cos(config.UF_mcs_hand_wheel(t))*B(self.P_rbs_input_shaft,self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2]).T),A(self.P_vbs_chassis),self.Mbar_vbs_chassis_jcs_input_bearing[:,0:1]])]]),self.L_mcs_hand_wheel])
        self.F_rbs_input_shaft_mcs_hand_wheel = Q_rbs_input_shaft_mcs_hand_wheel[0:3,0:1]
        Te_rbs_input_shaft_mcs_hand_wheel = Q_rbs_input_shaft_mcs_hand_wheel[3:7,0:1]
        self.T_rbs_input_shaft_mcs_hand_wheel = 0.5*multi_dot([E(self.P_rbs_input_shaft),Te_rbs_input_shaft_mcs_hand_wheel])
        Q_rbs_input_shaft_jcs_input_connect = -1*multi_dot([np.bmat([[np.eye(3, dtype=np.float64),np.zeros((1,3),dtype=np.float64).T],[B(self.P_rbs_input_shaft,self.ubar_rbs_input_shaft_jcs_input_connect).T,multi_dot([B(self.P_rbs_input_shaft,self.Mbar_rbs_input_shaft_jcs_input_connect[:,0:1]).T,A(self.P_rbs_connect_shaft),self.Mbar_rbs_connect_shaft_jcs_input_connect[:,0:1]])]]),self.L_jcs_input_connect])
        self.F_rbs_input_shaft_jcs_input_connect = Q_rbs_input_shaft_jcs_input_connect[0:3,0:1]
        Te_rbs_input_shaft_jcs_input_connect = Q_rbs_input_shaft_jcs_input_connect[3:7,0:1]
        self.T_rbs_input_shaft_jcs_input_connect = (-1*multi_dot([skew(multi_dot([A(self.P_rbs_input_shaft),self.ubar_rbs_input_shaft_jcs_input_connect])),self.F_rbs_input_shaft_jcs_input_connect]) + 0.5*multi_dot([E(self.P_rbs_input_shaft),Te_rbs_input_shaft_jcs_input_connect]))
        Q_rbs_output_shaft_jcs_output_connect = -1*multi_dot([np.bmat([[np.eye(3, dtype=np.float64),np.zeros((1,3),dtype=np.float64).T],[B(self.P_rbs_output_shaft,self.ubar_rbs_output_shaft_jcs_output_connect).T,multi_dot([B(self.P_rbs_output_shaft,self.Mbar_rbs_output_shaft_jcs_output_connect[:,0:1]).T,A(self.P_rbs_connect_shaft),self.Mbar_rbs_connect_shaft_jcs_output_connect[:,0:1]])]]),self.L_jcs_output_connect])
        self.F_rbs_output_shaft_jcs_output_connect = Q_rbs_output_shaft_jcs_output_connect[0:3,0:1]
        Te_rbs_output_shaft_jcs_output_connect = Q_rbs_output_shaft_jcs_output_connect[3:7,0:1]
        self.T_rbs_output_shaft_jcs_output_connect = (-1*multi_dot([skew(multi_dot([A(self.P_rbs_output_shaft),self.ubar_rbs_output_shaft_jcs_output_connect])),self.F_rbs_output_shaft_jcs_output_connect]) + 0.5*multi_dot([E(self.P_rbs_output_shaft),Te_rbs_output_shaft_jcs_output_connect]))
        Q_rbs_output_shaft_jcs_output_bearing = -1*multi_dot([np.bmat([[np.eye(3, dtype=np.float64),np.zeros((1,3),dtype=np.float64).T,np.zeros((1,3),dtype=np.float64).T],[B(self.P_rbs_output_shaft,self.ubar_rbs_output_shaft_jcs_output_bearing).T,multi_dot([B(self.P_rbs_output_shaft,self.Mbar_rbs_output_shaft_jcs_output_bearing[:,0:1]).T,A(self.P_vbs_chassis),self.Mbar_vbs_chassis_jcs_output_bearing[:,2:3]]),multi_dot([B(self.P_rbs_output_shaft,self.Mbar_rbs_output_shaft_jcs_output_bearing[:,1:2]).T,A(self.P_vbs_chassis),self.Mbar_vbs_chassis_jcs_output_bearing[:,2:3]])]]),self.L_jcs_output_bearing])
        self.F_rbs_output_shaft_jcs_output_bearing = Q_rbs_output_shaft_jcs_output_bearing[0:3,0:1]
        Te_rbs_output_shaft_jcs_output_bearing = Q_rbs_output_shaft_jcs_output_bearing[3:7,0:1]
        self.T_rbs_output_shaft_jcs_output_bearing = (-1*multi_dot([skew(multi_dot([A(self.P_rbs_output_shaft),self.ubar_rbs_output_shaft_jcs_output_bearing])),self.F_rbs_output_shaft_jcs_output_bearing]) + 0.5*multi_dot([E(self.P_rbs_output_shaft),Te_rbs_output_shaft_jcs_output_bearing]))

        self.reactions = {'F_rbs_input_shaft_jcs_input_bearing' : self.F_rbs_input_shaft_jcs_input_bearing,
                        'T_rbs_input_shaft_jcs_input_bearing' : self.T_rbs_input_shaft_jcs_input_bearing,
                        'F_rbs_input_shaft_mcs_hand_wheel' : self.F_rbs_input_shaft_mcs_hand_wheel,
                        'T_rbs_input_shaft_mcs_hand_wheel' : self.T_rbs_input_shaft_mcs_hand_wheel,
                        'F_rbs_input_shaft_jcs_input_connect' : self.F_rbs_input_shaft_jcs_input_connect,
                        'T_rbs_input_shaft_jcs_input_connect' : self.T_rbs_input_shaft_jcs_input_connect,
                        'F_rbs_output_shaft_jcs_output_connect' : self.F_rbs_output_shaft_jcs_output_connect,
                        'T_rbs_output_shaft_jcs_output_connect' : self.T_rbs_output_shaft_jcs_output_connect,
                        'F_rbs_output_shaft_jcs_output_bearing' : self.F_rbs_output_shaft_jcs_output_bearing,
                        'T_rbs_output_shaft_jcs_output_bearing' : self.T_rbs_output_shaft_jcs_output_bearing}
Exemple #33
0
from numpy.linalg import multi_dot

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

np.set_printoptions(precision=17)
dat = pd.read_csv('linear-regression.txt', header=None)
allval = dat.values

features_no_bias = allval[:, 0:2].T
xtemp1 = np.ones((1, 3000), dtype=float)
features = np.append(xtemp1, features_no_bias, axis=0)

target = np.array(allval[:, 2].T)

n = allval.shape[0]

feat = np.linalg.inv(np.dot(features, features.T))

w_opt = multi_dot([feat, features, target])
print("Optimum weights are ", w_opt)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(allval[:, 0], allval[:, 1], allval[:, 2])
x1 = np.linspace(0, 1, 100)
ax.plot(x1, x1,
        w_opt[0] + (np.multiply(w_opt[1], x1) + np.multiply(w_opt[2], x1)),
        '.r-')
plt.show()
    def compile(self, seq, registers):
        """Try to arrange a quantum circuit into a form suitable for Chip0.

        Args:
            seq (Sequence[Command]): quantum circuit to modify
            registers (Sequence[RegRefs]): quantum registers
        Returns:
            List[Command]: modified circuit
        Raises:
            CircuitError: the circuit does not correspond to Chip0
        """
        # pylint: disable=too-many-statements,too-many-branches
        # First, check if provided sequence matches the circuit template.
        # This will avoid superfluous compilation if the user is using the
        # template directly.
        try:
            seq = super().compile(seq, registers)
        except CircuitError:
            # failed topology check. Continue to more general
            # compilation below.
            pass
        else:
            return seq

        # first do general GBS compilation to make sure
        # Fock measurements are correct
        # ---------------------------------------------
        seq = GBSSpecs().compile(seq, registers)
        A, B, C = group_operations(seq,
                                   lambda x: isinstance(x, ops.MeasureFock))

        if len(B[0].reg) != self.modes:
            raise CircuitError("All modes must be measured.")

        # Check circuit begins with two mode squeezers
        # --------------------------------------------
        A, B, C = group_operations(seq, lambda x: isinstance(x, ops.S2gate))

        if A:
            raise CircuitError("Circuits must start with two S2gates.")

        # get circuit registers
        regrefs = {q for cmd in B for q in cmd.reg}

        if len(regrefs) != self.modes:
            raise CircuitError("S2gates do not appear on the correct modes.")

        # Compile the unitary: combine and then decompose all unitaries
        # -------------------------------------------------------------
        A, B, C = group_operations(
            seq, lambda x: isinstance(x, (ops.Rgate, ops.BSgate)))

        # begin unitary lists for mode [0, 1] and modes [2, 3] with
        # two identity matrices. This is because multi_dot requires
        # at least two matrices in the list.
        U_list01 = [np.identity(self.modes // 2, dtype=np.complex128)] * 2
        U_list23 = [np.identity(self.modes // 2, dtype=np.complex128)] * 2

        if not B:
            # no interferometer was applied
            A, B, C = group_operations(seq,
                                       lambda x: isinstance(x, ops.S2gate))
            A = B  # move the S2gates to A
        else:
            for cmd in B:
                # calculate the unitary matrix representing each
                # rotation gate and each beamsplitter
                # Note: this is done separately on modes [0, 1]
                # and modes [2, 3]
                modes = [i.ind for i in cmd.reg]
                params = par_evaluate(cmd.op.p)
                U = np.identity(self.modes // 2, dtype=np.complex128)

                if isinstance(cmd.op, ops.Rgate):
                    m = modes[0]
                    U[m % 2, m % 2] = np.exp(1j * params[0])

                elif isinstance(cmd.op, ops.BSgate):
                    m, n = modes

                    t = np.cos(params[0])
                    r = np.exp(1j * params[1]) * np.sin(params[0])

                    U[m % 2, m % 2] = t
                    U[m % 2, n % 2] = -np.conj(r)
                    U[n % 2, m % 2] = r
                    U[n % 2, n % 2] = t

                if set(modes).issubset({0, 1}):
                    U_list01.insert(0, U)
                elif set(modes).issubset({2, 3}):
                    U_list23.insert(0, U)
                else:
                    raise CircuitError(
                        "Unitary must be applied separately to modes [0, 1] and modes [2, 3]."
                    )

        # multiply all unitaries together, to get the final
        # unitary representation on modes [0, 1] and [2, 3].
        U01 = multi_dot(U_list01)
        U23 = multi_dot(U_list23)

        # check unitaries are equal
        if not np.allclose(U01, U23):
            raise CircuitError(
                "Interferometer on modes [0, 1] must be identical to interferometer on modes [2, 3]."
            )

        U = block_diag(U01, U23)

        # replace B with an interferometer
        B = [
            Command(ops.Interferometer(U01), registers[:2]),
            Command(ops.Interferometer(U23), registers[2:]),
        ]

        # decompose the interferometer, using Mach-Zehnder interferometers
        B = self.decompose(B)

        # Do a final circuit topology check
        # ---------------------------------
        seq = super().compile(A + B + C, registers)
        return seq
    def eval_constants(self):
        config = self.config

        self.F_rbs_input_shaft_gravity = np.array([[0], [0], [-9810.0*config.m_rbs_input_shaft]], dtype=np.float64)
        self.F_rbs_connect_shaft_gravity = np.array([[0], [0], [-9810.0*config.m_rbs_connect_shaft]], dtype=np.float64)
        self.F_rbs_output_shaft_gravity = np.array([[0], [0], [-9810.0*config.m_rbs_output_shaft]], dtype=np.float64)

        self.Mbar_rbs_input_shaft_jcs_input_bearing = multi_dot([A(config.P_rbs_input_shaft).T,triad(config.ax1_jcs_input_bearing)])
        self.Mbar_vbs_chassis_jcs_input_bearing = multi_dot([A(config.P_vbs_chassis).T,triad(config.ax1_jcs_input_bearing)])
        self.ubar_rbs_input_shaft_jcs_input_bearing = (multi_dot([A(config.P_rbs_input_shaft).T,config.pt1_jcs_input_bearing]) + -1*multi_dot([A(config.P_rbs_input_shaft).T,config.R_rbs_input_shaft]))
        self.ubar_vbs_chassis_jcs_input_bearing = (multi_dot([A(config.P_vbs_chassis).T,config.pt1_jcs_input_bearing]) + -1*multi_dot([A(config.P_vbs_chassis).T,config.R_vbs_chassis]))
        self.Mbar_rbs_input_shaft_jcs_input_bearing = multi_dot([A(config.P_rbs_input_shaft).T,triad(config.ax1_jcs_input_bearing)])
        self.Mbar_vbs_chassis_jcs_input_bearing = multi_dot([A(config.P_vbs_chassis).T,triad(config.ax1_jcs_input_bearing)])
        self.Mbar_rbs_input_shaft_jcs_input_connect = multi_dot([A(config.P_rbs_input_shaft).T,triad(config.ax1_jcs_input_connect)])
        self.Mbar_rbs_connect_shaft_jcs_input_connect = multi_dot([A(config.P_rbs_connect_shaft).T,triad(config.ax2_jcs_input_connect,triad(config.ax1_jcs_input_connect)[0:3,1:2])])
        self.ubar_rbs_input_shaft_jcs_input_connect = (multi_dot([A(config.P_rbs_input_shaft).T,config.pt1_jcs_input_connect]) + -1*multi_dot([A(config.P_rbs_input_shaft).T,config.R_rbs_input_shaft]))
        self.ubar_rbs_connect_shaft_jcs_input_connect = (multi_dot([A(config.P_rbs_connect_shaft).T,config.pt1_jcs_input_connect]) + -1*multi_dot([A(config.P_rbs_connect_shaft).T,config.R_rbs_connect_shaft]))
        self.Mbar_rbs_output_shaft_jcs_output_connect = multi_dot([A(config.P_rbs_output_shaft).T,triad(config.ax1_jcs_output_connect)])
        self.Mbar_rbs_connect_shaft_jcs_output_connect = multi_dot([A(config.P_rbs_connect_shaft).T,triad(config.ax2_jcs_output_connect,triad(config.ax1_jcs_output_connect)[0:3,1:2])])
        self.ubar_rbs_output_shaft_jcs_output_connect = (multi_dot([A(config.P_rbs_output_shaft).T,config.pt1_jcs_output_connect]) + -1*multi_dot([A(config.P_rbs_output_shaft).T,config.R_rbs_output_shaft]))
        self.ubar_rbs_connect_shaft_jcs_output_connect = (multi_dot([A(config.P_rbs_connect_shaft).T,config.pt1_jcs_output_connect]) + -1*multi_dot([A(config.P_rbs_connect_shaft).T,config.R_rbs_connect_shaft]))
        self.Mbar_rbs_output_shaft_jcs_output_bearing = multi_dot([A(config.P_rbs_output_shaft).T,triad(config.ax1_jcs_output_bearing)])
        self.Mbar_vbs_chassis_jcs_output_bearing = multi_dot([A(config.P_vbs_chassis).T,triad(config.ax1_jcs_output_bearing)])
        self.ubar_rbs_output_shaft_jcs_output_bearing = (multi_dot([A(config.P_rbs_output_shaft).T,config.pt1_jcs_output_bearing]) + -1*multi_dot([A(config.P_rbs_output_shaft).T,config.R_rbs_output_shaft]))
        self.ubar_vbs_chassis_jcs_output_bearing = (multi_dot([A(config.P_vbs_chassis).T,config.pt1_jcs_output_bearing]) + -1*multi_dot([A(config.P_vbs_chassis).T,config.R_vbs_chassis]))
Exemple #36
0
 def RMSE(self):
     reConsMatrix = multi_dot([self.C,self.U,self.R])
     row,column = self.matrix.shape
     print("RMSE "+str(sqrt((np.sum(np.square(reConsMatrix-self.matrix)))/(row*column))))
     print("MAE "+str(np.sum(np.abs(reConsMatrix -self.matrix))/(row*column)))
     return (sqrt((np.sum(np.square(reConsMatrix-self.matrix)))/(row*column)),(np.sum(np.abs(reConsMatrix -self.matrix))/(row*column)))
    def eval_pos_eq(self):
        config = self.config
        t = self.t

        x0 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1].T
        x1 = self.P_rbs_input_shaft
        x2 = A(x1)
        x3 = x2.T
        x4 = A(self.P_vbs_chassis)
        x5 = self.Mbar_vbs_chassis_jcs_input_bearing[:,2:3]
        x6 = self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2].T
        x7 = self.R_rbs_input_shaft
        x8 = -1*self.R_vbs_chassis
        x9 = (x7 + x8 + multi_dot([x2,self.ubar_rbs_input_shaft_jcs_input_bearing]) + -1*multi_dot([x4,self.ubar_vbs_chassis_jcs_input_bearing]))
        x10 = self.Mbar_vbs_chassis_jcs_input_bearing[:,0:1]
        x11 = -1*self.R_rbs_connect_shaft
        x12 = self.P_rbs_connect_shaft
        x13 = A(x12)
        x14 = self.R_rbs_output_shaft
        x15 = self.P_rbs_output_shaft
        x16 = A(x15)
        x17 = x16.T
        x18 = self.Mbar_vbs_chassis_jcs_output_bearing[:,2:3]
        x19 = -1*np.eye(1, dtype=np.float64)

        self.pos_eq_blocks = (multi_dot([x0,x3,x4,x5]),
        multi_dot([x6,x3,x4,x5]),
        multi_dot([x0,x3,x9]),
        multi_dot([x6,x3,x9]),
        (cos(config.UF_mcs_hand_wheel(t))*multi_dot([self.Mbar_rbs_input_shaft_jcs_input_bearing[:,1:2].T,x3,x4,x10]) + -1*sin(config.UF_mcs_hand_wheel(t))*multi_dot([self.Mbar_rbs_input_shaft_jcs_input_bearing[:,0:1].T,x3,x4,x10])),
        (x7 + x11 + multi_dot([x2,self.ubar_rbs_input_shaft_jcs_input_connect]) + -1*multi_dot([x13,self.ubar_rbs_connect_shaft_jcs_input_connect])),
        multi_dot([self.Mbar_rbs_input_shaft_jcs_input_connect[:,0:1].T,x3,x13,self.Mbar_rbs_connect_shaft_jcs_input_connect[:,0:1]]),
        (x14 + x11 + multi_dot([x16,self.ubar_rbs_output_shaft_jcs_output_connect]) + -1*multi_dot([x13,self.ubar_rbs_connect_shaft_jcs_output_connect])),
        multi_dot([self.Mbar_rbs_output_shaft_jcs_output_connect[:,0:1].T,x17,x13,self.Mbar_rbs_connect_shaft_jcs_output_connect[:,0:1]]),
        (x14 + x8 + multi_dot([x16,self.ubar_rbs_output_shaft_jcs_output_bearing]) + -1*multi_dot([x4,self.ubar_vbs_chassis_jcs_output_bearing])),
        multi_dot([self.Mbar_rbs_output_shaft_jcs_output_bearing[:,0:1].T,x17,x4,x18]),
        multi_dot([self.Mbar_rbs_output_shaft_jcs_output_bearing[:,1:2].T,x17,x4,x18]),
        (x19 + multi_dot([x1.T,x1])),
        (x19 + multi_dot([x12.T,x12])),
        (x19 + multi_dot([x15.T,x15])),)