Example #1
0
def main():
    a = matrix.Matrix(2, 3)
    print('a =')
    print(a)
    b = matrix.Matrix(3, 2)
    print('b =')
    print(b)
    print('a+1 = ')
    print(a + 1)
    print('a-2 = ')
    print(a - 2)
    print('a+b = ')
    print(a + b)
    print('a-b = ')
    print(a - b)
    print('a+a = ')
    print(a + a)
    print('b-b = ')
    print(b - b)
    print('a*2 = ')
    print(a * 2)
    print('a*b = ')
    print(a * b)
    print('a.transpose = ')
    print(a.transpose())
    print('a*(b.transpose) = ')
    print(a * (b.transpose()))
    a = matrix.Matrix(4)
    print('a =')
    print(a)
    print('a.determinate = ', a.determinate())
    def test_el_wise_mul(self):
        mat1 = matrix.Matrix([[2, 3], [8, 1]])
        mat2 = matrix.Matrix([[5, 1], [6, 7]])
        mat = mat1.el_wise_mul(mat2)
        res = matrix.Matrix([[10, 3], [48, 7]])

        self.assertEqual(res, mat)
Example #3
0
 def setUp(self):
     self.elements1 = [
         [1,2,3],
         [4,5,6]
     ]
     self.matrix1 = matrix.Matrix(self.elements1)
     self.elements2 = [
         [0,0,0],
         [4,0,6],
         [1,0,0]
     ]
     self.matrix2 = matrix.Matrix(self.elements2)
     self.elements3 = [
         [4,2,6],
         [1,11,5],
         [3,12,9]
     ]
     self.matrix3 = matrix.Matrix(self.elements3)
     self.elements4 = [
         [0,2,6],
         [4,0,0],
         [1,11,5],
         [3,12,9]
     ]
     self.matrix4 = matrix.Matrix(self.elements4)
     self.elements5 = [
         [0,0,0,0,2,6],
         [0,4,0,4,0,0],
         [0,0,0,1,11,5],
         [0,0,0,3,12,9]
     ]
     self.matrix5 = matrix.Matrix(self.elements5)
Example #4
0
def getBFGS(cD, params_new, params_k, A_k):
    s_vector = M.subVek(params_new, params_k)
    y_vector = M.subVek(cV.gradPhi(params_new, cD), cV.gradPhi(params_k, cD))

    # s_Matrix and y_Matix is a column, not a row, therefor copyTrans
    s_Matrix = M.Matrix([s_vector]).copyTrans()
    y_Matrix = M.Matrix([y_vector]).copyTrans()

    dividend = A_k.mult(s_Matrix)
    dividend = dividend.mult(dividend.copyTrans())
    divisor = M.scal(s_vector, A_k.image(s_vector))
    quotient = dividend
    quotient.scale(1.0 / divisor)

    rankOneMod = M.subMatrix(A_k, quotient)

    dividend2 = y_Matrix.mult(y_Matrix.copyTrans())

    # here could be a division through zero. If this occurence, then I should just translate params_new a liiiitle bit...
    divisor2 = M.scal(y_vector, s_vector)

    quotient = dividend2
    #print( 'vectors are')
    #print(y_vector)
    #print( s_vector)
    #print( cV.gradPhi(params_new , cD))
    quotient.scale(1.0 / divisor2)

    rankTwoMod = M.addMatrix(rankOneMod, quotient)

    return rankTwoMod
Example #5
0
    def testEquals_otherIsEqual_returnsTrue(self):
        m = matrix.Matrix(1, 2)
        m[0][1] = 'a'
        other = matrix.Matrix(0, 0)
        other.matrix_ = [[0, 'a']]

        self.assertEqual(m, other)
Example #6
0
    def testSubtraction_emptyMatrices_returnsEmptyMatrix(self):
        m1 = matrix.Matrix(0, 0)
        m2 = matrix.Matrix(0, 0)

        m3 = m1 - m2

        self.assertTrue(m3.empty())
Example #7
0
    def testAddition_emptyMatrices_returnsEmptyMatrix(self):
        m1 = matrix.Matrix(0, 0)
        m2 = matrix.Matrix(0, 0)

        m3 = m1 + m2

        self.assertTrue(m3.empty())
    def test_matmul(self):
        mat1 = matrix.Matrix([[2, 3], [8, 1]])
        mat2 = matrix.Matrix([[2], [1]])
        res = matrix.Matrix([[7], [17]])

        self.assertEqual(res, mat1 @ mat2)
        self.assertEqual(res, mat1 * mat2)
Example #9
0
def scale_op(path, img, points, height, width, x, y):
    imgTensor = pic_strong(img)
    m = matrix.Matrix(height, width)
    m_point = matrix.Matrix(height, width)
    m.scale(1 / x, 1 / y)
    m_point.scale(x, y)
    theta = torch.from_numpy(m.to_theta())
    img_torch = imgTensor.type(torch.DoubleTensor)
    grid = F.affine_grid(theta.unsqueeze(0),
                         img_torch.unsqueeze(0).size(), False)
    output = F.grid_sample(img_torch.unsqueeze(0), grid)

    newpoints = m_point.dot_point_68(points)
    pointTensor = pointToTensor(newpoints[0])

    new_img = tensorToImage(output)
    out_img = new_img.resize((Config.IMAGE_SIZE, Config.IMAGE_SIZE))
    # out_img = tfs.functional.resize(
    #     new_img, [Config.IMAGE_SIZE, Config.IMAGE_SIZE], Image.BICUBIC
    # )
    imgTensor = pic_strong(out_img)
    imgTensor = biaozhunhua(imgTensor)

    return (
        imgTensor.type(torch.DoubleTensor),
        pointTensor,
        path[0],
        new_img,
        newpoints[1],
    )
Example #10
0
    def inverse(self):
        """
        Calculates the inverse of a 1x1 or 2x2 Matrix.
        """
        if not self.is_square():
            raise (ValueError, "Non-square Matrix does not have an inverse.")
        if self.h > 2:
            raise (NotImplementedError,
                   "inversion not implemented for matrices larger than 2x2.")

        # TODO - your code here
        import matrix
        if self.h == 1:
            m = matrix.Matrix([[1 / self.g[0][0]]])
            return m
        if self.h == 2:
            if self.determinant() == 0:
                raise ZeroDivisionError(
                    "Matrix does not have an inverse if determinant equal to zero"
                )
            else:
                a = self.g[0][0]
                b = self.g[0][1]
                c = self.g[1][0]
                d = self.g[1][1]
                temp = 1 / self.determinant()
                inverse = [[temp * d, -temp * b], [-temp * c, temp * a]]
                m = matrix.Matrix(inverse)
                return m
Example #11
0
 def test_identitymatrixmultiplication(self):
     identity_matrix = matrix.Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1)
     second_matrix = matrix.Matrix(2, 3, 1, 5, 3, 12, 54, 32, 12)
     result_matrix1 = identity_matrix * second_matrix
     result_matrix2 = second_matrix * identity_matrix
     self.assertEqual(second_matrix._values, result_matrix1._values)
     self.assertEqual(second_matrix._values, result_matrix2._values)
Example #12
0
def densities(T):

	'''
	This function takes in a temperature T
	computes all of our number densities
	returns a Matrix object containing all of the number densities
	'''
	
	###(3x3)
	b = matrix.Matrix((3 , 1) , ([[0] , [0], [1]]))
	A = matrix.Matrix((3 , 3))
	
	A.elements[0][0] = ((get_B(1 , 2) * J(T , 1 , 2) + get_B(1 , 3) * J(T , 1 , 3))).value
	A.elements[0][1] = -1 * (get_A(2 , 1) + get_B(2 , 1) * J(T , 2 , 1)).value
	A.elements[0][2] = -1 * (get_A(3 , 1) + get_B(3 , 1) * J(T , 3 , 1)).value
	A.elements[1][1] = (get_B(2 , 1) * J(T , 2 , 1) + get_A(2 , 1) + get_B(2 , 3) * J(T , 2 , 3)).value
	A.elements[1][0] = -1 * (get_B(1 , 2) * J(T  , 1 , 2)).value
	A.elements[1][2] = -1 * (get_B(3 , 2) * J(T , 3  ,2) + get_A(3 , 2)).value
	'''
	A.elements[2][0] = -1 * (get_B(1 , 3) * J(T , 1 , 3)).value
	A.elements[2][1] = -1 * (get_B(2 , 3) * J(T , 2 , 3)).value
	A.elements[2][2] = (get_B(3 , 1) * J(T , 3 , 1) + get_A(3 , 1) + get_A(3, 2) + get_B(3 , 2) * J(T , 3 , 2)).value
	'''
	A.elements[2][0] = 1
	A.elements[2][1] = 1
	A.elements[2][2] = 1
	x = matrix.solve_eq(A , b)
	return x
Example #13
0
def test():
    I2 = m.Matrix([[1, 0], [0, 1]])
    I2_neg = m.Matrix([[-1, 0], [0, -1]])

    zero = m.Matrix([[0, 0], [0, 0]])

    m1 = m.Matrix([[1, 2, 3], [4, 5, 6]])

    m2 = m.Matrix([[7, -2], [-3, -5], [4, 1]])

    m1_x_m2 = m.Matrix([[13, -9], [37, -27]])

    m2_x_m1 = m.Matrix([[-1, 4, 9], [-23, -31, -39], [8, 13, 18]])

    m1_m2_inv = m.Matrix([[1.5, -0.5], [2.0555556, -0.722222222]])

    top_ones = m.Matrix([[1, 1], [0, 0]])

    left_ones = m.Matrix([[1, 0], [1, 0]])

    assert equal(-I2, I2_neg)
    assert equal(I2 + I2_neg, zero)
    assert equal(m1 * m2, m1_x_m2)
    assert equal(m2 * m1, m2_x_m1)
    assert equal(m1_x_m2.inverse(), m1_m2_inv)
    assert equal(I2.inverse(), I2)
    assert equal(top_ones.T(), left_ones)
    assert equal(left_ones.T(), top_ones)
    assert equal(top_ones - left_ones.T(), m.zeroes(2, 2))
    assert (4 * m.identity(5)).trace() == 20

    print("Congratulations! All tests pass. Your Matrix class is working"
          "as expected.")
Example #14
0
 def test_zeromatrixmultiplication(self):
     zero_matrix = matrix.Matrix(*[0] * 9)
     second_matrix = matrix.Matrix(*range(1, 10))
     result_matrix1 = zero_matrix * second_matrix
     result_matrix2 = second_matrix * zero_matrix
     self.assertEqual(zero_matrix._values, result_matrix1._values)
     self.assertEqual(zero_matrix._values, result_matrix2._values)
Example #15
0
    def __mul__(self, other):
        """
        Defines the behavior of * operator (matrix multiplication)
        """
        #
        # TODO - your code here
        #

        product = []
        current_rowA = []
        current_rowB = []
        Other = m.Matrix(other.g)
        transB = Other.T()
        row_results = []
        for i in range(len(self.g)):
            for j in range(len(other.g[0])):
                result = 0
                current_rowA = self.g[i]
                current_rowB = transB[j]
                for k in range(len(current_rowB)):
                    result += current_rowA[k] * current_rowB[k]
                row_results.append(result)
            product.append(row_results)
            row_results = []
            matrixMul = m.Matrix(product)
        return matrixMul
Example #16
0
    def test_multiplicate_fail_dimensions(self):

        A = matrix.Matrix(2, 2)
        B = matrix.Matrix(4, 1)

        with self.assertRaises(matrix.InvalidMatrixDimensions):
            matrix.Matrix.multiplicate(A, B)
Example #17
0
def o3():
    M = [
        models.Matrix(read_matrix_with_space(f'o3_m{i}')) for i in range(1, 5)
    ]
    v = models.Matrix(read_matrix_with_space('o3_v'))
    b2 = models.Matrix(read_matrix_with_space('o3_b2'))
    # A - матрица линейного отображения
    A = models.Matrix([[0] * 4 for _ in range(2)])
    for i, m in enumerate(M):
        p = m * v  # умножаем один из базисных векторов M на v
        b = deepcopy(b2)
        b.add_column(
            p.columns[0]
        )  # добавляем полученный вектор к базису в Q^2 как третий столбец
        print('b=', b, sep='\n')
        b.to_step()  # методом Гаусса приводим к ступеньчатому виду
        # Выражаем p через базис в Q^2 (считаем координаты)
        x2 = b.rows[1][2]
        x1 = -b.rows[0][1] * x2 + b.rows[0][2]
        # И записываем координаты в матрицу отображения
        A.rows[0][i] = x1
        A.rows[1][i] = x2
        print(f'x1={x1}, x2={x2}')
        print('\n')
    # Выводим матрицу отображения
    print(A)
    print(A * models.Matrix([[1], [0], [0], [0]]))
 def test_is_square(self):
     print("\n\n####################")
     print("#  test_is_square  #")
     print("####################")
     print("\nMatrix\n")
     m1 = matrix.Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
     print(m1.g)    
     print("\n") 
     print(m1.is_square())      
     self.assertTrue(m1.is_square() == True)
     print("\nMatrix\n")
     m2 = matrix.Matrix([[1, 2],[3, 4]])
     print(m2.g)    
     print("\n") 
     print(m2.is_square())      
     self.assertTrue(m2.is_square() == True)
     print("\nMatrix\n")
     m3 = matrix.Matrix([[1, 2, 3], [4, 5, 6]])
     print(m3.g)    
     print("\n") 
     print(m3.is_square())      
     self.assertTrue(m3.is_square() == False)
     print("\nMatrix\n")
     m4 = matrix.Matrix([[1],[3]])
     print(m4.g)    
     print("\n") 
     print(m4.is_square())      
     self.assertTrue(m4.is_square() == False)       
Example #19
0
 def test_substraction(self):
     first_matrix = matrix.Matrix(12, 34, 21, 5)
     second_matrix = matrix.Matrix(5, 13, 12, 32)
     result1 = first_matrix - second_matrix
     result2 = second_matrix - first_matrix
     self.assertEqual([(7, 21), (9, -27)], result1._values)
     self.assertEqual([(-7, -21), (-9, 27)], result2._values)
Example #20
0
def test_matrix_multiplication():
    a = matrix.Matrix([[-1, 4, -2]])
    b = matrix.Matrix([[1], [2], [3]])
    c = a * b
    d = b * a
    assert isinstance(c, matrix.Matrix), "The product must be a Matrix as well!"
    assert c.data == [[1]], "The product is not correct!"
    assert d.data == [[-1, 4, -2], [-2, 8, -4], [-3, 12, -6]], "The product is not correct!"
    def init_gradient_matrix(self):
        self.gradient_matrix = mt.Matrix()
        self.gradient_matrix.set(self.weight_matrix.num_rows,
                                 self.weight_matrix.num_cols)

        self.gradient_mean_matrix = mt.Matrix()
        self.gradient_mean_matrix.set(self.weight_matrix.num_rows,
                                      self.weight_matrix.num_cols)
Example #22
0
def test_assertions_for_creation_with_constructor():
    with pytest.raises(AssertionError):
        matrix.Matrix([[1, 2, 3], [1, 2], [1, 2, 3]]) #Your class is supposed to assert that the Matrix is not ill-shaped!

    with pytest.raises(AssertionError):
        matrix.Matrix([[1, 2, 3], [1, 2, 'platypus'], [1, 2, 3]]) #Your class is supposed to assert that it can only be constructed with ints or floats

    matrix.Matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
Example #23
0
def o2():
    ls = read_matrix_with_space('o2')  # Для суммы
    matrix = models.Matrix(ls, mod=5)
    b2 = models.Matrix([[x.numerator for x in matrix.columns[4]]], mod=5)
    b1 = models.Matrix([[x.numerator for x in matrix.columns[3]]], mod=5)
    to_step(matrix)

    print(f'b2={b2}, b1={b1}')
    print(f'b2 - b1 = {b2-b1}')
Example #24
0
def o2_sup():
    ls = read_matrix_with_space('o2')
    an = [models.Matrix([[x] for x in l], mod=5) for l in ls[:3]]
    bn = [models.Matrix([[x] for x in l], mod=5) for l in ls[3:]]
    coefs_2 = [(i, j) for i in range(5) for j in range(5)]
    xs = {bn[0] * b1 + bn[1] * (b1 * 4) + bn[2] * b3 for b1, b3 in coefs_2}
    print('\n\n'.join(map(str, xs)))
    print(len(xs))
    print(str(bn[0] + bn[1] * 4))
Example #25
0
 def test_addition(self):
     first_matrix = matrix.Matrix(*range(1, 10))
     second_matrix = matrix.Matrix(*range(1, 19, 2))
     result1 = first_matrix + second_matrix
     result2 = second_matrix + first_matrix
     self.assertEqual([(2, 5, 8), (11, 14, 17), (20, 23, 26)],
                      result1._values)
     self.assertEqual([(2, 5, 8), (11, 14, 17), (20, 23, 26)],
                      result2._values)
Example #26
0
def test():

    m1 = m.Matrix([[1, 2, 3], [4, 5, 6]])

    m2 = m.Matrix([[7, -2], [-3, -5], [4, 1]])

    m1_x_m2 = m.Matrix([[13, -9], [37, -27]])

    assert equal(m1 * m2, m1_x_m2), "Error in your __mul__ function"
 def normalEquation(self, inputs= None): #uses matricies to skip the iterative process, more about this method can be looked up
     if inputs == None:
         inputs = self.inputs
     
     inputMatrix = matrix.Matrix(inputs)
     outputMatrix = matrix.Matrix([[y] for y in self.outputs])
     inverse = (inputMatrix.transpose() * inputMatrix).inverse()
     weights = inverse * inputMatrix.transpose() * outputMatrix
     
     return [weights[x][0] for x in range(weights.rows)]
Example #28
0
    def test_multiplicate1(self):
        A = matrix.Matrix(2, 3, [[1, 2, 3], [2, 3, 4]])
        B = matrix.Matrix(3, 5,
                          [[2, 1, 1, 2, 1], [1, 2, 1, 6, 1], [3, 4, 2, 1, 2]])

        C = matrix.Matrix.multiplicate(A, B)
        self.assertEqual(C.get_height(), A.get_height())
        self.assertEqual(C.get_width(), B.get_width())

        self.assertEqual(C.data, [[13, 17, 9, 17, 9], [19, 24, 13, 26, 13]])
Example #29
0
def diffGetNextVertex(u, volume, point):
    B = M.Matrix([[-u[1]], [u[0]]])
    A = M.Matrix([[-u[0], -u[1]]])
    C = B.mult(A)
    c = M.scal(point, u)
    c = 2 * volume / (c**2)
    C.scale(c)
    # Matrix.plus oder Matrix.add verwenden?
    C.add(M.idMatrix(2))
    return C
    def test_get_transpose(self):
        mat = matrix.Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        res = matrix.Matrix([[1, 4, 7], [2, 5, 8], [3, 6, 9]])

        self.assertEqual(res, mat.get_transpose())

        mat = matrix.Matrix([[1, 4, 3], [8, 2, 6], [7, 8, 3], [4, 9, 6], [7, 8, 1]])
        res = matrix.Matrix([[1, 8, 7, 4, 7], [4, 2, 8, 9, 8], [3, 6, 3, 6, 1]])

        self.assertEqual(res, mat.get_transpose())