Example #1
0
 def testInv(self):
     matA = Matrix([[1, 2, 3], [0, 1, 2], [1, 2, 4]])
     matAinv = matA.inv()
     c = matA.prod(matAinv).getRows([1, 2, 3])
     self.assertTrue(
         matA.prod(matAinv).getRows([1, 2, 3]) == [[1, 0, 0], [0, 1, 0],
                                                   [0, 0, 1]])
Example #2
0
 def testGetMatrixFromColumnFail(self):
     with self.assertRaises(Exception):
         matA = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 0]])
         matA.getMatrixFromColumn(initialX=1,
                                  initialY=1,
                                  height=-4,
                                  width=3)
    def Train(self, inputs, targets):
        # Calc errors
        self.FeedForward(inputs)
        targets = Matrix.FromArray(targets)
        output_errors = Matrix.Subtract(targets, self.outputs)
        weights_ho_T = Matrix.Transpose(self.weights_ho)
        hidden_errors = Matrix.Multiply(weights_ho_T, output_errors)
        # Calc gradients
        gradient_o = Matrix.StaticMap(self.outputs, dsigmoid)
        gradient_o.ElementMultiply(output_errors)
        gradient_o.ElementMultiply(self.lr)
        hidden_T = Matrix.Transpose(self.hidden)
        delta_weights_ho = Matrix.Multiply(gradient_o, hidden_T)

        gradient_h = Matrix.StaticMap(self.hidden, dsigmoid)
        gradient_h.ElementMultiply(hidden_errors)
        gradient_h.ElementMultiply(self.lr)
        input_T = Matrix.Transpose(self.inputs)
        delta_weights_ih = Matrix.Multiply(gradient_h, input_T)

        # Adjusting weights and biases
        # self.weights_ih.Display()
        self.weights_ih.Add(delta_weights_ih)
        self.bias_h.Add(gradient_h)
        # delta_weights_ho.Display()
        self.weights_ho.Add(delta_weights_ho)
        self.bias_o.Add(gradient_o)
def test_jacobi_seidel_3x3():
    #Example from https://www.maa.org/press/periodicals/loci/joma/iterative-methods-for-solving-iaxi-ibi-gauss-seidel-method
    # solution x=(1, 2, -1).T
    A = Matrix([[4, -1, -1], [-2, 6, 1], [-1, 1, 7]])
    b = Matrix([[3], [9], [-6]])
    solution = solve_jacobi_seidel(A, b)
    assert solution.is_close(Matrix([[1], [2], [-1]]))
Example #5
0
 def testSubtraction(self):
     
     testMatrix1 = Matrix()
     testMatrix2 = Matrix()
     
     testMatrix3 = testMatrix1 - testMatrix2
     
     for row in range(4):
         for col in range(4):
             self.assertTrue(testMatrix3.getValue(row, col) == 0)
             
     testMatrix1.setValue(0, 3, 2.5)
     testMatrix1.setValue(2, 2, 4.2)
     testMatrix1.setValue(3, 0, -301)
     
     testMatrix2.setValue(0, 3, -1)
     testMatrix2.setValue(0, 0, -2)
     testMatrix2.setValue(3, 0, 2)
     
     testMatrix4 = testMatrix1 - testMatrix2
     
     self.assertTrue(testMatrix4.getValue(0, 3) == 3.5)
     self.assertTrue(testMatrix4.getValue(2, 2) == 4.2)
     self.assertTrue(testMatrix4.getValue(3, 0) == -303)
     self.assertTrue(testMatrix4.getValue(0, 0) == 2.0)
     self.assertTrue(testMatrix4.getValue(2, 1) == 0)
Example #6
0
class MainWindow(Frame):

    def __init__(self, master, rows, columns):
        Frame.__init__(self, master)

        self.matrix = Matrix(master, rows, columns)
        self.matrix.grid(row=0, column=0)

        self.game = Game(rows, columns)
        self.game.set_matrix(self.matrix)

        self.start_button = Button(master, text="Start")
        self.start_button.grid(row=1, column=0)
        self.start_button["command"] = self.game.start_clicked

        self.quit_button = Button(master, text="Quit")
        self.quit_button.grid(row=1, column=1)
        self.quit_button["command"] = self.quit

        self.master = master
        master.title("Life")

        # override the "X" close button
        self.master.protocol("WM_DELETE_WINDOW", self.quit)

    def quit(self):
        print "quitting"
        self.game.quit_clicked()
        self.master.quit()
Example #7
0
class Network:
	
	def __init__(self, inp_length, hid_length, out_length):
		self.inp_size = inp_length
		self.hid_size = hid_length
		self.out_size = out_length
		self.inputs = Matrix(1, inp_length)
		self.hidden = Matrix(1, hid_length)
		self.outputs = Matrix(1, out_length)
		self.weights_ih = Matrix (inp_length, hid_length)
		self.weights_ho = Matrix (hid_length, out_length)
		randomise(self.weights_ih)
		randomise(self.weights_ho)
		
	def feedforward(self):
		self.hidden = self.inputs.multiply(self.weights_ih)
		self.hidden = sigmoid(self.hidden)
		self.outputs = softmax(self.hidden.multiply(self.weights_ho))
		

	def print_network(self):
		print(self.inputs.matrix)
		print()
		print()
		print(self.weights_ih.matrix)
		print()
		print()		
		print(self.hidden.matrix)
		print()
		print()
		print(self.weights_ho.matrix)
		print()
		print()
		print(self.outputs.matrix)
Example #8
0
    def __init__(self, *domains):
        self.domainList = list(domains)

        self.size = sum([len(i.nodes) * i.dofs for i in self.domainList])
        self.dofs = self.size
        self.totalConstraints = sum(
            [len(i.constraintList) for i in self.domainList])

        self.physics = {'gravity': 0}

        self.stiffnessMatrix = Matrix(0)
        self.stiffnessMatrixInverse = Matrix(0)
        self.displacementVector = Vector(0)
        self.loadVector = Vector(0)

        self.solver = None
        self.inverseFlag = True

        self.couplingList = []
        self.couplingListRHS = []

        self.dampingList = {}
        self.ivDisplacementList = {}

        self.__assembleConstraints__()
Example #9
0
def findLU(n, matrixA):
    # Find the L U for the decomposition
    L = Matrix(dims=(n, n), fill=0)
    U = Matrix(dims=(n, n), fill=0)

    # Fill the value of L
    for i in range(n):
        L[i, i] = 1

    # Calculate for the lower, upper matrix, i for row index, j for col index
    for i in range(n):
        for j in range(n):
            tmp = matrixA[i, j]
            for k in range(n):
                if j != k:
                    tmp = tmp - L[i, k] * U[k, j]

            # lower matrix
            if i > j:
                if U[j, j] != 0:
                    L[i, j] = tmp / U[j, j]
                else:
                    L[i, j] = tmp
            # Upper matrix
            else:
                if L[j, j] != 0:
                    U[i, j] = tmp / L[j, j]
                else:
                    U[i, j] = tmp
    return L, U
Example #10
0
def lanczos(A):
    k = len(A)

    b = Vector.rand(n=k)
    q = [Vector.new(n=k) for i in range(2)]
    q[1] = b / abs(b)

    b = [0]
    a = [0]

    for i in range(1, int(2 * sqrt(k))):
        z = Vector((A * q[i]).transpose()[0])
        a.append(float(Matrix([q[i]]) * z))
        z = z - q[i] * a[i] - q[i-1] * b[i-1]
        for j in q:
            z -= j * (z * j)
        for j in q:
            z -= j * (z * j)
        b.append(abs(z))
        if b[i] == 0:
            break
        q.append(z / b[i])

    Q = Matrix(q[-k-1:-1]).transpose()
    T = Q.transpose() * A * Q
    return (Q, T, )
def open_last_sts(data_path, head):
    #here data_path should be the Lucile folder
    mtrx_path = data_path
    head = head + "_0001.mtrx"
    my_matrix = Matrix(mtrx_path, head)
    #here mtrx_path should be the folder with the head file
    keys = list(my_matrix.IDs.keys())
    last_ID = keys[-1]
    while last_ID:
        if not last_ID in my_matrix.IDs.keys():
            last_ID -= 1
            continue
        if my_matrix.IDs[last_ID]['hasDI']:
            last_num = my_matrix.IDs[last_ID]['nums'][-1]
            while last_num:
                try:
                    V, didv = my_matrix.getDIDV(last_ID, last_num)
                    break
                except TypeError:
                    last_num -= 1
            #plt.ion()
            #plt.plot(V, didv)
            #plt.pause(0.1)
            #plt.show()
            #plt.pause(3)
            #plt.close()
            #plt.ioff()
            return V, didv
            break
        else:
            last_ID -= 1
    return None, None
Example #12
0
def main():
    m = Matrix(5, 2)
    b = Matrix(5, 2)
    print("show matrix :", m, sep='\n')
    m += 10
    print("after adding 10:", m, sep='\n')
    b = b + 20
    m = m + b
    print("after adding matrix b:", m, sep='\n')
    m.randomize()
    print("after randomize :", m, sep='\n')
    m *= 3
    print("after multiply by 3 :", m, sep='\n')
    d = Matrix(2, 3)
    g = Matrix(3, 3)
    g.matrix = [
        [3, 5, 8],
        [2, 6, 6],
        [7, 9, 4]
    ]
    d += 5
    h = d * g
    print("after multiply d :\n{}\nby g :\n{}\nres :\n{}".format(d, g, h))
    h = g.transpose()
    print("after transpose :\n{}".format(h))
def test_jacobi_example_4x4():
    A = Matrix([[10, -1, 2, 0], [-1, 11, -1, 3], [2, -1, 10, -1],
                [0, 3, -1, 8]])
    b = Matrix([[6], [25], [-11], [15]])

    solution = solve_jacobi(A, b)
    assert solution == Matrix([[1], [2], [-1], [1]])
def parseFile(self):
    matrices = []
    for i, line in enumerate(self):
        line = line.rstrip()
        if i == 0:
            problemTitle = line
        elif i == 1:
            problemSize = line
        elif i == 2:
            correctAnswer = line
        else:
            if not line.startswith("\t"):
                #this is a matrix
                newMatrix = Matrix(line)
                matrices.append(newMatrix)
            elif not line.startswith("\t\t"):
                #this is an object
                line = line.strip()
                newObject = Object(line)
                newMatrix.objects[line] = newObject
            else:
                #this is an attribute (key-value pair)
                line = line.strip()
                keyValue = line.split(":")
                newObject.attributes.update({keyValue[0]: keyValue[1]})

    problem = Problem(problemTitle, problemSize, correctAnswer, matrices)
    return problem
Example #15
0
    def makeGraphFromEdges1(self, edges):
        """
        Constructs a directional graph from edges (a list of tuple).
        Each tuple contains 2 vertices.
        For example, P -> Q is written as ('P', 'Q').

        @param edges: edges
        @type edges: list of 2-element tuple

        @status: Tested method
        @since: version 0.1
        """
        if type(edges) != list: raise GraphParameterError('Edges must be a \
                                list of tuples')
        from Set import Set
        from Matrix import Matrix
        vertices = list(Set([x[0] for x in edges] + [x[1] for x in edges]))
        adj = Matrix(len(vertices))
        adj = adj.m
        for e in edges:
            row = vertices.index(e[0])
            col = vertices.index(e[1])
            # fill values into lower triangular matrix
            adj[row][col] = adj[row][col] + 1
        adj.insert(0, vertices)
        self.makeGraphFromAdjacency(adj)
Example #16
0
 def testWrongMatrixSumOrders(self):
     with self.assertRaises(Exception):
         matA = Matrix([[1, 1, 1, 1, 1], [2, 2, 2, 5], [3, 3, 3, 5, 3],
                        [3, 3, 3, 5, 3], [5, 5, 5, 5, 5]])
         matB = Matrix([[1, 1, 1, 1, 1], [2, 2, 2, 5, 1], [3, 3, 3, 5, 3],
                        [3, 3, 3, 5, 3], [5, 5, 5, 5, 5]])
         matA.sum(matB)
Example #17
0
    def Jacobi(self, iteration=5):
        """
        iterate throught the jacobi method to solve the system
        """
        Id = Identity(len(self.A.matrix))
        #exctract the Diagonal from the matrix
        Diag = [[self.A[i][j] \
                if i == j else 0 \
                for j in range(len(self.A.matrix))] \
                for i in range(len(self.A.matrix))]
        Diag = Matrix(Diag)
        inv_diag = Diag.reverse_diag()
        X_k = Matrix([[0]\
                      for i in range(len(self.A.matrix)) ])

        # Id check
        # inv_diag check
        # A check
        # Y check
        for i in range(iteration):
            B = (Id - (inv_diag * self.A))
            X_k = (B * X_k) + (inv_diag * self.Y)
            # x = Bx + (ID - B) A^-1 * Y
            # B = Id - D^-1A
            # pour avoir (Id - B) A^-1 * Y
            # sans le A^-1
            # soit x = Bx + D^-1 * Y
            # (I - D^-1 * A) * X_k + D^-1 * Y
            #erreur potentielle de calcul, ou systeme insolvable.

        return (X_k)
Example #18
0
    def __init__(self, parent=None):
        super(GLWidget, self).__init__(parent)

        self.setFocusPolicy(Qt.StrongFocus)

        self.object = 0
        self.xRot = 0
        self.yRot = 0
        self.zRot = 0
        self.translateX = 0.0
        self.translateY = 0.0
        self.zoom = -15.0
        self.ctlPressed = False

        self.matrix = Matrix(5, 5, 5)

        self.lastPos = QPoint()

        self.selectedX = 0
        self.selectedY = 0
        self.selectedZ = 4

        self.trolltechGreen = QColor.fromCmykF(0.40, 0.0, 1.0, 0.0)
        self.trolltechPurple = QColor.fromCmykF(0.39, 0.39, 0.0, 0.0)
        self.Black = QColor.fromCmykF(0.0, 0.0, 0.0, 0.0, 0.0)

        self.selectedColor = self.trolltechGreen
Example #19
0
    def makeGraphFromEdges2(self, edges):
        """
        Constructs an un-directional graph from edges (a list of tuple).
        Each tuple contains 2 vertices.
        An un-directional graph is implemented as a directional graph where
        each edges runs both directions.

        @param edges: list of edges
        @type edges: list of 2-element tuples"""
        if type(edges) != list:
            raise GraphParameterError('Edges must be a \
                                list of tuples')
        from Set import Set
        from Matrix import Matrix
        vertices = list(Set([x[0] for x in edges] + [x[1] for x in edges]))
        adj = Matrix(len(vertices))
        adj = adj.m
        for e in edges:
            row = vertices.index(e[0])
            col = vertices.index(e[1])
            # fill values into lower triangular matrix
            adj[row][col] = adj[row][col] + 1
            # repeat on the upper triangular matrix for undirectional graph
            adj[col][row] = adj[col][row] + 1
        adj.insert(0, vertices)
        self.makeGraphFromAdjacency(adj)
Example #20
0
   def quad(self, g, quad):
      # Enable alpha blending/transparency
      self.vbuffer.sync()

      gl.glUseProgram(self.program.id)
      gl.glEnable(gl.GL_BLEND)
      gl.glEnable(gl.GL_DEPTH_TEST)
      gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
      
      # Bind texture
      gl.glUniform1i(self.program.tex, 0) 
      gl.glBindTexture(gl.GL_TEXTURE_2D, quad.texture.id)
      
      # Set up geometry transforms
      worldMatrix = Matrix.scale(quad.width, quad.height, 1) 
      worldMatrix = Matrix.translate(quad.x, quad.y, 0) * worldMatrix
      worldViewProjectionMatrix = g.viewProjectionMatrix * worldMatrix
      #worldViewProjectionMatrix = g.viewProjectionMatrix
      gl.glUniformMatrix4fv(self.program.worldViewProjectionMatrix, 1, 0, 
                            worldViewProjectionMatrix.data)

      # Draw geometry
      gl.glBindVertexArray(self.vao)
      gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)
      gl.glBindVertexArray(0)
Example #21
0
    def makeGraphFromEdges1(self, edges):
        """
        Constructs a directional graph from edges (a list of tuple).
        Each tuple contains 2 vertices.
        For example, P -> Q is written as ('P', 'Q').

        @param edges: edges
        @type edges: list of 2-element tuple

        @status: Tested method
        @since: version 0.1
        """
        if type(edges) != list:
            raise GraphParameterError('Edges must be a \
                                list of tuples')
        from Set import Set
        from Matrix import Matrix
        vertices = list(Set([x[0] for x in edges] + [x[1] for x in edges]))
        adj = Matrix(len(vertices))
        adj = adj.m
        for e in edges:
            row = vertices.index(e[0])
            col = vertices.index(e[1])
            # fill values into lower triangular matrix
            adj[row][col] = adj[row][col] + 1
        adj.insert(0, vertices)
        self.makeGraphFromAdjacency(adj)
Example #22
0
 def makeGraphFromEdges2(self, edges):
     """
     Constructs an un-directional graph from edges (a list of tuple).
     Each tuple contains 2 vertices.
     An un-directional graph is implemented as a directional graph where
     each edges runs both directions.
     
     @param edges: list of edges
     @type edges: list of 2-element tuples"""
     if type(edges) != list: raise GraphParameterError('Edges must be a \
                             list of tuples')
     from Set import Set
     from Matrix import Matrix
     vertices = list(Set([x[0] for x in edges] + [x[1] for x in edges]))
     adj = Matrix(len(vertices))
     adj = adj.m
     for e in edges:
         row = vertices.index(e[0])
         col = vertices.index(e[1])
         # fill values into lower triangular matrix
         adj[row][col] = adj[row][col] + 1
         # repeat on the upper triangular matrix for undirectional graph
         adj[col][row] = adj[col][row] + 1
     adj.insert(0, vertices)
     self.makeGraphFromAdjacency(adj)
Example #23
0
 def get_matrix(self):
     rows, cols = self.get_size()
     matrix     = Matrix(rows, cols)
     for child in self.get_children():
         box = self.find_box_child(child)
         matrix.set(child, box.left, box.top, box.right, box.bottom)
     return matrix
Example #24
0
 def test_slice(self):
     A = Matrix([1, 2, 3, 4],
                [5, 6, 7, 9],
                [1, 2, 3, 4])
     s = A.slice(0, 2)
     self.assertEqual(s, Matrix(
         [3, 4], [7, 9], [3, 4]))
Example #25
0
 def get_matrix(self):
     rows, cols = self.get_size()
     matrix = Matrix(rows, cols)
     for child in self.get_children():
         box = self.find_box_child(child)
         matrix.set(child, box.left, box.top, box.right, box.bottom)
     return matrix
Example #26
0
def spline_cubic(data, value, is_natural=True, first_der=0, last_der=0):
    """
    Using cubic plaine to calculate an interpolation of a point according to data points
    :param data: the data points pairs of x,y
    :param value: The value to calculate it's interpolation
    :param is_natural: a boolean if the cubic splaine is natural or not
    :param first_der: in case of none natural cubic splaine it's the first derived of the function
    :param last_der: in case of none natural cubic splaine it's the last derived of the function
    :return: A vector with the results of each function corresponding to each pair of points
    """
    if len(data) < 2:
        return 'failed'

    def x(i):
        return data[i][0]

    def y(i):
        return data[i][1]

    def h(i):
        return x(i + 1) - x(i)

    n = len(data)
    A = np.identity(n)
    b = list(((y(i + 1) - y(i)) / (h(i)) - (y(i) - y(i - 1)) / (h(i - 1))
              for i in range(1, n - 1)))
    if not is_natural:
        b.insert(0, ((y(1) - y(0)) / h(0)) - first_der)
        b.append((last_der - ((y(n - 1) - y(n - 2)) / h(n - 2))))
        A[0][0] = h(0) / 3
        A[0][1] = h(0) / 6
        A[n - 1][n - 2] = h(n - 2) / 6
        A[n - 1][n - 1] = h(n - 2) / 3
    else:  # handles natural splaine.
        b.insert(0, 0)
        b.append(0)
    for i in range(1, n - 1):
        A[i][i - 1] = h(i - 1) / 6
        A[i][i] = ((h(i - 1) + h(i)) / 3)
        A[i][i + 1] = h(i) / 6
    Mat = Matrix(A, b)
    print("The matrix and the solution vector of the cubic spline:\n", A, b)
    print("\ncalculating the matrix results with gauss seidel.....")

    Mi = Mat.gauss_seidel(list(0.0 for _ in range(len(b))))
    print("Mi - vector: ", Mi)
    print("\n")
    results = [0.0 for _ in range(n - 1)]
    for i in range(n - 1):
        print("S{0}(x)= ({1}(x-{2})/{3})-({4}(x-{5})/{3})+"
              "({6}/6)[((x-{2})^3)/{3}) -{3}(x-{2}))] - "
              "({7}/6)[((x-{5})^3)/{3}) - {3}(x-{5})]\n".format(
                  i, y(i + 1), x(i), h(i), y(i), x(i + 1), Mi[i + 1], Mi[i]))
        results[i] = (y(i + 1) * (value - x(i)) / h(i)) - (y(i) * (value - x(i + 1)) / h(i)) + \
                     (Mi[i + 1] / 6) * ((((value - x(i)) ** 3) / h(i)) - h(i) * (value - x(i))) - \
                     (Mi[i] / 6) * ((((value - x(i + 1)) ** 3) / h(i)) - h(i) * (value - x(i + 1)))

    print(results)
    return results
Example #27
0
def test_single():
    """
    Test single element
    :return:
    """
    a = Matrix([[1]])
    x = solve_gauss(a, Matrix())
    assert x == []
Example #28
0
def creating(q):
    while True:
        size = randint(2, 7)
        a = Matrix(a=size, b=size, random=True)
        b = Matrix(a=size, b=size, random=True)
        print(f"Сгенерированы матрицы:\n{a}\n{b}\n--------------------------")
        q.put([a, b])
        sleep(8)  # Эта функция выполняется намного быстрее умножения, поэтому ждём
Example #29
0
 def __init__(self, nRows, nCols):
     self.rows = nRows
     self.cols = nCols
     self.matrix = Matrix(nRows, nCols)
     # fill the sheet with zero numbercells
     for row in range(self.rows):
         for col in range(self.cols):
             self.updateValue(row, col, "0")
Example #30
0
 def feedforword(self, inputs):
     if len(inputs) == self.sizes[0]:
         output = Matrix(1, len(inputs), [inputs]).transpose()
         for i in range(len(self.sizes) - 1):
             output = self.weights[i] * output + self.biases[i]
             output = output.apply(sigmoid)
         return output
     raise Exception("Invalid input length")
Example #31
0
def Matrix_Rotation(n, theta):
    I = Matrix(n, n)
    if (n == 2):
        return Matrix([
            [cos(theta), -sin(theta)],
            [sin(theta), cos(theta)],
        ])
    return I
Example #32
0
 def testGetMatrixFromColumnException(self):
     with self.assertRaises(Exception):
         matA = Matrix([[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3],
                        [4, 4, 4, 4, 4], [5, 5, 5, 5, 5]])
         matA.getMatrixFromColumn(initialX=2,
                                  initialY=2,
                                  height=3,
                                  width=10)
def main():
    matrix = Matrix(2, 4)
    matrix.list_fill([[9, 9], [1, 10], [6, 5], [6, 2]])
    collection = Collection()
    collection.matrix_as_collection(matrix)
    print(collection)
    collected = Collection.compute_basis(collection)
    print(collected)
Example #34
0
    def calculate_normal(self, triangle):
        vertex_0, vertex_1, vertex_2 = triangle

        edge_1 = Matrix.subtract(vertex_1, vertex_0)
        edge_2 = Matrix.subtract(vertex_2, vertex_0)
        normal = Matrix.cross_product(edge_1, edge_2)
        normal = Matrix.normalize(normal)
        return normal
Example #35
0
 def __init__(self,rows,cols):
     self.rows = rows
     self.cols = cols
     self.matrix = Matrix(rows, cols)
     # fill the sheet with zero numbercells
     for row in range(self.rows):
         for col in range(self.cols):
             self.modifyValue(row, col, "0")
Example #36
0
 def __init__(self):
     self.rows = 3
     self.cols = 5
     self.matrix = Matrix(3, 5)
     # fill the sheet with zero numbercells
     for row in range(self.rows):
         for col in range(self.cols):
             self.updateValue(row, col, "0")
Example #37
0
def test_transpose_square():
    """
    Check transpose of square 3x3 matrix
    :return:
    """
    A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    A_transpose = Matrix([[1, 4, 7], [2, 5, 8], [3, 6, 9]])
    assert A.T == A_transpose
Example #38
0
 def setCenterPosition(self, center: Vector) -> None:
     if self._mesh_data:
         m = Matrix()
         m.setByTranslation(-center)
         self._mesh_data = self._mesh_data.getTransformed(m).set(
             center_position=center)
     for child in self._children:
         child.setCenterPosition(center)
Example #39
0
    def set_covariance(self):
        for i in self.matrices:
            a = i.subtract(self.mean)
            a_transpose = Matrix(a.get_data())
            a_transpose.transpose()
            b = a_transpose.multiply(a)
            self.covariance = self.covariance.add(b)

        self.covariance.scaler(1 / len(self.matrices))
Example #40
0
 def __init__(self):
     self.data = []
     self.matrices = []
     self.mean = Matrix([[0, 0]])
     self.covariance = Matrix([[0, 0], [0, 0]])
     self.setup()
     self.set_mean()
     self.set_covariance()
     print(len(self.matrices))
Example #41
0
 def reset(self):
     '''resets the whole sugarscape'''
     self.agents = []
     self.gov.tax_rate = self.tax_rate
     Matrix.__init__(self,51,51)
     self.agents = []
     self.populate_sugarscape()
     self.timestamp = 0
     return True
Example #42
0
 def test_setrowcol(self):
     A = Matrix([1, 2, 3, 4],
                [5, 6, 7, 8])
     A.set_row(0, [4, 3, 2, 1])
     self.assertEqual(A, Matrix([4, 3, 2, 1],
                                [5, 6, 7, 8]))
     A.set_col(2, [9, 8])
     self.assertEqual(A, Matrix([4, 3, 9, 1],
                                [5, 6, 8, 8]))
Example #43
0
def cg(A,b):
	#guess x all 0s
	x = Matrix(i=A.columns,j=1)

	#set r and p
	r = b.subtract(A.multiply(x))
	p = b.subtract(A.multiply(x))
	
	r_norm_inf = 0
	for i in range(1,r.rows+1):
		v = r.get(i,1)
		if (v > r_norm_inf):
			r_norm_inf = v
	r_norm_2 = 0
	r_norm_2 = math.sqrt(r.transpose().multiply(r).get(1,1))
	
	iteration = 1
	
	while( r_norm_2 > LIMITERROR):
		p_t = p.transpose()
		alpha = p_t.multiply(r).get(1,1) /  p_t.multiply(A.multiply(p)).get(1,1)
		
		
		# a_p for alpha*p
		a_p = copy.deepcopy(p)
		for i in range(1,a_p.rows+1):
			for j in range(1,a_p.columns+1):
				a_p.set(i,j,a_p.get(i,j)*alpha)
		
		x = x.add(a_p)
		
		r = b.subtract(A.multiply(x))
		beta = -1 * (p_t.multiply(A.multiply(r)).get(1,1) / p_t.multiply(A.multiply(p)).get(1,1))

		
		# b_p for beta*p
		b_p = p #no need to copy (as we update cell by cell of p to b_p and we don't need it later)
		for i in range(1,b_p.rows+1):
			for j in range(1,b_p.columns+1):
				b_p.set(i,j,p.get(i,j)*beta)
		p = r.add(b_p)
		
		# compute r norms and f.write
		r_norm_inf = 0
		for i in range(1,r.rows+1):
			v = r.get(i,1)
			if (v > r_norm_inf):
				r_norm_inf = v
		
		r_norm_2 = math.sqrt(r.transpose().multiply(r).get(1,1))
		
		f.write(str(iteration)+","+str(r_norm_inf)+","+str(r_norm_2)+"\n")
		iteration+=1
	
	f.write(",,,"+str(iteration-1))
	return x
Example #44
0
    def test_construction(self):
        m1 = Matrix(2, 3)
        self.assertEqual(m1.size(), [2, 3])
        # Verify the matrix is filled with 0s
        self.assertEqual(m1.data, [[0 for i in range(3)] for j in range(2)])

        m2 = Matrix([0, 1, 2], [3, 4, 5], [6, 7, 8])
        self.assertEqual(m2.size(), [3, 3])
        # Verify the matrix has values 0-8
        self.assertEqual(m2.data, [[(j * 3 + i) for i in range(3)] for j in range(3)])
Example #45
0
    def test_multplication(self):
        # Test dot products

        # Row vectors
        v1 = Matrix([1, 2])
        v2 = Matrix([5], [6])
        self.assertEqual(v1 * v2, 17)
        self.assertEqual(v1 * [5, 6], 17)
        # Column vectors
        v1 = Matrix([10], [7])
        v2 = Matrix([5 ], [8])
        self.assertEqual(v1 * v2.transposed(), Matrix([50, 80], [35, 56]))

        # Test matrix scalar multiplication
        m = Matrix([1, 4, 5, 6], [3, 8, 9, 2], [9, 12, 4, 13])
        self.assertEqual((m * 4).data, [[(m[j][i] * 4) for i in range(m.cols)] for j in range(m.rows)])

        # Test matrix multiplication
        m1 = Matrix([2, 3], [4, 5], [6, 7])
        m2 = Matrix([1, 2, 3], [4, 5, 6])
        r = Matrix([14, 19, 24], [24, 33, 42], [34, 47, 60])
        self.assertEqual(m1 * m2, r)
        self.assertEqual(m1 * [[1, 2, 3], [4, 5, 6]], r)

        # Test swapping rows of a matrix with a permutation matrix
        m = Matrix([11, 9 , 24, 2],
                   [1 , 5 , 2 , 6],
                   [3 , 17, 18, 1],
                   [2 , 5 , 7 , 1])
        p = Matrix([1, 0, 0, 0], 
                   [0, 0, 1, 0],
                   [0, 0, 0, 1],
                   [0, 1, 0, 0])
        self.assertEqual(p * m, Matrix(
                   [11, 9 , 24, 2],
                   [3 , 17, 18, 1],
                   [2 , 5 , 7 , 1],
                   [1 , 5 , 2 , 6]))
        # Test swapping of cols of a matrix with the same permutation matrix
        self.assertEqual(m * p, Matrix(
                   [11, 2, 9 , 24 ],
                   [1 , 6, 5 , 2  ],
                   [3 , 1, 17, 18 ],
                   [2 , 1, 5 , 7  ]))
        # Multiplication of matrix with a matrix of 3 columns and list of 3 components
        self.assertEqual(
            Matrix([24 , 1, 8 ],
                   [6  , 0, 2 ],
                   [-12, 1, -3]) * Matrix([1], [9], [-2]), 
                   Matrix([17], [2], [3]))
        self.assertEqual(
            Matrix([24 , 1, 8 ],
                   [6  , 0, 2 ],
                   [-12, 1, -3]) * [1, 9, -2], 
                   Matrix([17], [2], [3]))
Example #46
0
    def add_padding(self, padding, matrix):

        #validate inputs
        if (not type(padding) is int or padding <= 0 or not type(matrix) is Matrix):
            raise LedError("Invalid inputs. Padding must be a positive, non-zero integer")

        output = Matrix(matrix.m, padding)
        output = output.concatenate(matrix)
        output = output.concatenate(matrix.m, padding)

        return output
Example #47
0
    def convert_message_led(self):

        checker = False
        output = Matrix(1,1)
        for char in self.message:
            temp = self.char_map[char]
            if (temp):
                if (checker):
                    output = output.concatenate(temp)
                else:
                    output.copy(temp)
                    checker = True
        return output
Example #48
0
 def __init__(self, num_agents = 500, max_sugar=5, sugar_growth_rate=.5,
              agent_vision=3, agent_metabolism=4, tax_rate=.5):
     ''' The sugarscape is a matrix of Location objects.'''
     Matrix.__init__(self, 51, 51)
     self.max_sugar = max_sugar
     self.sugar_growth_rate = sugar_growth_rate
     self.agent_vision = agent_vision
     self.agent_metabolism = agent_metabolism
     self.tax_rate = tax_rate
     self.agents = []
     self.total_wealth = 0
     self.num_agents = num_agents
     self.timestamp = 0
     self.gov = Government(tax_rate=self.tax_rate, sugarscape=self)
     self.populate_sugarscape()
Example #49
0
    def testCreation(self):

        testMatrix = Matrix()
        
        for row in range(4):
            for col in range(4):
                self.assertTrue(testMatrix.getValue(row, col) == 0)
                
        testMatrix.setValue(0, 0, 1.893)
        testMatrix.setValue(2, 1, -200.1)
        testMatrix.setValue(3, 2, 4)
        
        self.assertTrue(testMatrix.getValue(0, 0) == 1.893)
        self.assertTrue(testMatrix.getValue(2, 1) == -200.1)
        self.assertTrue(testMatrix.getValue(3, 2) == 4)
Example #50
0
def QRalg(m):
    from copy import deepcopy as copy
    from math import cos, sin, atan, pi
    def get_rotate_matrix(n, i, j, angle):
        m = Matrix.new(n, n)
        for k in range(n):
            if k not in [i, j]:
                m[k][k] = 1
        s = sin(angle)
        c = cos(angle)
        m[i][j] = -s
        m[j][i] = s
        m[i][i] = c
        m[j][j] = c
        return m

    m = copy(m)
    n = len(m)

    u = Matrix.new(n, n)
    for i in range(n):
        u[i][i] = 1

    iter_n = 1
    f = True
    while f and iter_n < 1000:
        q = 0
        qi, qj = 0, 0
        for i in range(n):
            for j in range(n):
                if i != j and abs(m[i][j]) > q:
                    q, qi, qj = abs(m[i][j]), i, j
        angle = pi / 4
        if abs(m[qi][qi] - m[qj][qj]) > 0.000001:
            angle = atan(2 * m[qi][qj] / (m[qi][qi] - m[qj][qj])) / 2
        
        rm = get_rotate_matrix(n, qi, qj, angle)
        rmt = rm.transpose()
        nm = rmt * m * rm

        u = u * rm 

       #l.write('{}: '.format(iter_n))
       #l.write(nm)
        s = 0
        for i in range(n):
            for j in range(n):
                if i != j:
                    s += nm[i][j] ** 2

        f = abs(s) > (0.1 ** 5)
        m = copy(nm)
        iter_n += 1

    values = Vector([m[i][i] for i in range(n)])
    vectors = u.transpose()
    for i in range(len(vectors)):
        if abs(vectors[i][-1]) > 0.001:
            vectors[i] *= 1/vectors[i][-1]
    return (values, vectors, )
Example #51
0
 def getEquilibriumMatrix(self):
     self.matrix = []
     for node in self.nodes:
         self.addXEquation(node)
         self.addYEquation(node)
     self.matrix = Matrix(self.matrix)
     return self.matrix
Example #52
0
    def compute_led_screen (text, padding):

        #validate inputs
        if (not type(text) is str or not type(padding) is int or padding <= 0):
            raise LedError("Only message strings are supported and padding must be a positive, non-zero integer")
        
        #pad pixels left
        output = Matrix(self.board_height, padding)

        for char in text:
            addition = self.char_map[char]
            output = output.concatenate(addition)

        #pad pixels right
        output = output.concatenate(Matrix(self.board_height, padding))

        return output
Example #53
0
 def test_swap(self):
     m = Matrix([1, 2, 3], [4, 5, 6])
     m.swap(0, 1)
     self.assertEqual(m, Matrix([4, 5, 6], [1, 2, 3]))
     m = Matrix([1, 2], [3, 4], [5, 6], [7, 8], [9, 10])
     m.swap(0, 4)
     m.swap(1, 3)
     # Middle row shouldn't move
     m.swap(2, 2)
     self.assertEqual(m, Matrix([9, 10], [7, 8], [5, 6], [3, 4], [1, 2]))
Example #54
0
   def init(self):
      # Initialize the renderer, set up the Window.
      glfw.init()
      glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
      glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
      glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)
      glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
      glfw.window_hint(glfw.DECORATED, gl.GL_TRUE)
      glfw.window_hint(glfw.DECORATED, gl.GL_TRUE)
      glfw.window_hint(glfw.RESIZABLE, gl.GL_FALSE)

      width = Config.windowWidth
      height = Config.windowHeight

      self.aspect = width/height

      # Initialize the window
      self.window = glfw.create_window(width, height, "Magic", None, None)
      glfw.make_context_current(self.window)
      self.renderer = Renderer()
      self.quad = []
      self.text = []

      # Set up camera
      self.viewMatrix = Matrix.identity()

      # Set up view transform. View is always 16 units high, and 16 * aspect units
      # wide. The extra space outside of a 4:3 ratio is unused, to make sure that
      # all the cards always fit in a 4:3 aspect monitor. 
      vHeight = 2
      vWidth = vHeight * self.aspect
      self.projectionMatrix = Matrix.ortho(-vWidth/2, vWidth/2, vHeight/2, -vHeight/2, -1, 1)
      self.viewProjectionMatrix = self.projectionMatrix * self.viewMatrix

      # Set up viewport
      fbWidth, fbHeight = glfw.get_framebuffer_size(self.window)
      gl.glViewport(0, 0, fbWidth, fbHeight)
      q = Quad(Texture('Images/Sen Triplets.jpg'))
      # Natural resolution of cards is 480x680
      cardAspect = 480/680
      q.x = 0
      q.y = 0
      q.height = .8
      q.width = q.height * cardAspect
      self.quad.append(q)
    def eval(self, destinations):
        """Produce a travel time matrix from the origins to all destinations"""
        if isinstance(destinations, str):
            destinations = PointSet(destinations)

        mat = Matrix(len(self._origins), len(destinations))

        graphId = self._graph.getId()

        if not destinations._samples.has_key(graphId):
            destinations.link(self._graph)

        destSamples = destinations._samples[graphId]

        for i in xrange(len(self._origins)):
            mat.setRow(i, destSamples.eval(self.results[i]))

        return mat
    def __init__(self, group_id, matrix_size):
        # Determine the sizes of all the matrices (these are the same) and
        # use it to assign addresses to each of them.
        matrices_size = Matrix.calculate_size(4, matrix_size, matrix_size)
        address_A, address_B, address_C = Address.assign_object_sizes(group_id, [matrices_size, matrices_size, matrices_size])

        # Construct actual matrices on assigned addresses.
        self.matrix_A = Matrix(address_A, 4, matrix_size, matrix_size)
        self.matrix_B = Matrix(address_B, 4, matrix_size, matrix_size)
        self.matrix_C = Matrix(address_C, 4, matrix_size, matrix_size)
Example #57
0
 def test_rowcol(self):
     m = Matrix([1, 2, 3], [4, 5, 6])
     self.assertEqual(m.row(0), [1, 2, 3])
     self.assertEqual(m.row(1), [4, 5, 6])
     # row() should only return a copy
     m.row(1)[1] = 0
     self.assertEqual(m[1][1], 5)
     self.assertEqual(m.col(0), [1, 4])
     self.assertEqual(m.col(1), [2, 5])
     self.assertEqual(m.col(2), [3, 6])
     # col() should only return copy
     m.col(1)[1] = 0
     self.assertEqual(m[1][1], 5)
Example #58
0
    def test_subtraction(self):
        m1 = Matrix(4, 4)
        m2 = Matrix([0 , 1 , 2 , 3 ],
                    [4 , 5 , 6 , 7 ],
                    [8 , 9 , 10, 11],
                    [12, 13, 14, 15])
        res = m1 - m2
        m1 -= m2
        self.assertEqual(res.size(), [4, 4])
        self.assertEqual(res.data, [[-(j * 4 + i) for i in range(4)] for j in range(4)])
        self.assertEqual(m1.data,  [[-(j * 4 + i) for i in range(4)] for j in range(4)])

        m3 = Matrix([4, 5, 2, 9],
                    [2, 1, 2, 1])
        m4 = Matrix([2 , 1, 9, 11],
                    [12, 4, 2, 12])
        r,c = m3.size()
        # Data should be componenet wise addition
        self.assertEqual((m3 - m4).data, [[(m3[j][i] - m4[j][i]) for i in range(c)] for j in range(r)])
        m4 += 3
Example #59
0
 def set_distances(self):
     for i in range(1, 15):
         temp = []
         for j in range(1, 15):
             x1 = self.points[i].get_data()[0][0]
             y1 = self.points[i].get_data()[0][1]
             x2 = self.points[j].get_data()[0][0]
             y2 = self.points[j].get_data()[0][1]
             temp.append(math.hypot(x2 - x1, y2 - y1))
         self.temp_dist.append(temp)
     self.distance = Matrix(self.temp_dist)
Example #60
0
File: 14.py Project: 21zaber/MAI
def get_rotate_matrix(n, i, j, angle):
    m = Matrix.new(n, n)
    for k in range(n):
        if k not in [i, j]:
            m[k][k] = 1
    s = sin(angle)
    c = cos(angle)
    m[i][j] = -s
    m[j][i] = s
    m[i][i] = c
    m[j][j] = c
    return m