def test_should_multiply_itself_by_1x1_matrix(self): matrix = Matrix(1, 1, 2) other_matrix = Matrix(1, 1, 1337) matrix.multiply(other_matrix) self.assertEquals(2 * 1337, matrix.get_item(0, 0))
def test_should_substract_other_10x10_matrix(self): matrix = Matrix(10, 10, 1338) other_matrix = Matrix(10, 10, 1) matrix.subtract(other_matrix) self.assertEquals(1337, matrix.get_item(9, 9))
def test_should_substract_other_1x1_matrix(self): matrix = Matrix(1, 1, 1338) other_matrix = Matrix(1, 1, 1) matrix.subtract(other_matrix) self.assertEquals(1337, matrix.get_item(0, 0))
def test_should_add_itself_to_other_10x10_matrix(self): matrix = Matrix(10, 10, 1) other_matrix = Matrix(10, 10, 1336) matrix.add(other_matrix) self.assertEquals(1337, matrix.get_item(9, 9))
def test_should_multiply_itself_by_10x10_matrix(self): matrix = Matrix(10, 10, 2) other_matrix = Matrix(10, 10, 1337) matrix.multiply(other_matrix) self.assertEquals(2 * 1337, matrix.get_item(9, 9))
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)
def test_iter_over_one_row(self): m = Matrix(3, 3) m[1][0] = 1 m[1][1] = 2 m[1][2] = 3 self.assertEqual([x for x in m.row(1)], [1, 2, 3]) self.assertEqual([x for x in m[1]], [1, 2, 3])
def matrix(self): back = -0.6 m = Matrix(4, 4) m.matrix[0] = [1.8 * self.prp_z / ((self.xmax - self.xmin) * (self.prp_z - back)), 0, ((self.xmax + self.xmin) - 1.8 * self.prp_x) / ((self.xmax - self.xmin) * (self.prp_z - back)), -((self.xmax + self.xmin) * self.prp_z) / ((self.xmax - self.xmin) * (self.prp_z - back)) ] m.matrix[1] = [0.0, 1.8 * self.prp_z / ((self.ymax - self.ymin) * (self.prp_z - back)), ((self.ymax + self.ymin) - 1.8 * self.prp_y) / ((self.ymax - self.ymin) * (self.prp_z - back)), -((self.ymax + self.ymin) * self.prp_z) / ((self.ymax - self.ymin) * (self.prp_z - back)) ] m.matrix[2] = [0.0, 0.0, 1.0 / (self.prp_z - back), -(self.prp_z) / (self.prp_z - back) ] m.matrix[3] = [0, 0, 0, 1 ] return m
def setUp(self): self.ecm = [[1, 1],[1, 0]] self.ec = Matrix(["Bearing", "Belt"], ["Import Mechanical", "Export Mechanical"] , lol_to_dict(self.ecm)) self.cfm = [[0,3],[1,0]] self.cf = Matrix(["Creep", "Fatigue"], ["Bearing", "Belt"], lol_to_dict(self.cfm)) self.cfpm = [[1,2],[5,0]] self.cfp = Matrix(["Creep", "Fatigue"], ["Bearing", "Belt"], lol_to_dict(self.cfpm)) self.efm = [[1,3],[0,3]] self.ef = Matrix(["Creep", "Fatigue"], ["Import Mechanical", "Export Mechanical"], lol_to_dict(self.efm)) self.l1m = [[2,5],[0,5]] self.l1 = Matrix(["Creep", "Fatigue"], ["Import Mechanical", "Export Mechanical"], lol_to_dict(self.l1m)) self.l2m = [[1,1],[0,1]] self.l2 = Matrix(["Creep", "Fatigue"], ["Import Mechanical", "Export Mechanical"], lol_to_dict(self.l2m)) self.c1m = [[5,2],[1,2]] self.c1 = Matrix(["Creep", "Fatigue"], ["Import Mechanical", "Export Mechanical"], lol_to_dict(self.c1m)) self.c2m = [[3,2],[1,2]] self.c2 = Matrix(["Creep", "Fatigue"], ["Import Mechanical", "Export Mechanical"], lol_to_dict(self.c2m))
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)
def main(): r = 66 c = 66 s = 7 test = Matrix(rows=r, columns=c, side=s) test.random_matrix() test.run()
def train(self, vector): matrix_2 = Matrix(vector) matrix_1 = Matrix(matrix_2.transpose()) matrix_3 = matrix_2 * matrix_1 identity = Matrix.identity(len(vector)) matrix_4 = matrix_3 - identity self.weight = self.weight + matrix_4
def main(): if len(argv) < 4: print "Usage: <num eigenvectors> <tolerance> <text file>" return data = load_matrix(argv[3]) k = int(argv[1]) epsilon = float(argv[2]) rows = len(data) cols = len(data[0]) A = Matrix(rows, cols, data) res, vals = power_method(k, epsilon, A) Vecs = Matrix(rows, k) for i in range(rows): for j in range(k): Vecs.data[i][j] = res[j].data[i][0] f1 = open('vecs.txt','w') f2 = open('vals.txt','w') # TODO fix formatting for i in range(rows): for j in range(k): f1.write(str(Vecs.data[i][j]) + ' ') f1.write('\n') for i in range(k): f2.write(str(vals[i]) + '\n') f1.close() f2.close()
def compute(self): filename = self.getInputFromPort("filename") f = open(filename.name, 'r') # read metadata _type = f.readline() rows = int(f.readline().strip()) cols = int(f.readline().strip()) # read attributes attributes = f.readline().split(';') # read id, values and class values = np.zeros((rows, cols)) ids = [] labels = [] for r in range(rows): line = f.readline().split(';') ids.append(r) labels.append(line[0]) values[r,] = np.array([float(val) for val in line[1:-1]]) #klass = float(line[-1]) matrix = Matrix() matrix.values = values matrix.ids = ids matrix.labels = labels matrix.attributes = attributes self.setResult('matrix', matrix)
def parse_Matrix(testset): print "Parsing text file "+ testset + " into Matrix instance" f=open(testset, "r") mat_list = [] # this will be returned res = [] # contains list of list that will be changed to a matrix res_len = -1 for line in f.readlines(): if line.startswith("test"): res.append([]) res_len += 1 else: res[res_len].append(line.rstrip(" \r\n").split(" ")) for elem in res: if(type(elem) == int): mat = Matrix(1,1) mat.matrix = elem mat_list.append(mat) else: print elem mat = Matrix(len(elem), len(elem[0])) # Matrix(2,10) for r in range(mat.row): # 2 for c in range(mat.col): # 10 mat.matrix[r][c] = int(elem[r][c]) mat_list.append(mat) return mat_list
def test_should_add_itself_to_other_1x1_matrix(self): matrix = Matrix(1, 1, 1) other_matrix = Matrix(1, 1, 1336) matrix.add(other_matrix) self.assertEquals(1337, matrix.get_item(0, 0))
def testColumns(self): matrix = Matrix([1, 3, 4], [-3, 2.5, 8], [3, 6, 1], [3, 0, 5]) self.assertEquals( matrix.rows(), [[1, 3, 4], [-3, 2.5, 8], [3, 6, 1], [3, 0, 5]]) self.assertEquals( matrix.columns(), [[1, -3, 3, 3], [3, 2.5, 6, 0], [4, 8, 1, 5]])
def testAdjugate(self): matrix = Matrix([2, 0, 0], [0, 2, 0], [0, 0, 2]) self.assertEquals( Matrix([4, 0, 0], [0, 4, 0], [0, 0, 4]), matrix.adjugate()) self.assertEquals( Matrix([7, -3], [-2, 1]), Matrix([1, 3], [2, 7]).adjugate())
def test_adding_rows(self): columns = 2 rows = 3 matrix = Matrix(rows, columns) self.assertRaises(ValueError, matrix.setRow, 1, [1, 2, 3]) matrix.setRow(2, [2, 5]) self.assertEqual(matrix.getRow(1), [0, 0]) self.assertEqual(matrix.getRow(2), [2, 5])
def test_matrix_save(): m, n = 2, 2 matrix = Matrix(m, n) matrix.colorize(0, 1, 'X') matrix.save('/tmp/matrix.bmp') with open('/tmp/matrix.bmp') as f: assert str(matrix) == f.read()
def get_udata_matrix(): """There are 943 users, 1682 movies. This makes the matrix.""" A = Matrix(943,1682) lines = open('ml-100k/u.data','r').readlines() for line in lines: l = line.split() A.data[int(l[0])-1][int(l[1])-1] = int(l[2]) return A
def test_adding_some_values(self): columns = 2 rows = 3 matrix = Matrix(rows, columns) matrix.setValue(2, 1, 2) matrix.setValue(3, 2, 6) self.assertEqual(2, matrix.getValue(2, 1)) self.assertEqual(6, matrix.getValue(3, 2))
class TestMatrix(TestCase): def setUp(self): self.m1 = Matrix([[1, 2], [3, 4]]) self.m2 = Matrix([[-1, 5], [0, 9]]) self.m3 = Matrix([[-1, 5, 4], [0, 9, 1], [4, 5, 2]]) self.m4 = Matrix([[-1, 5], [0, 9], [3, 2]]) def test_bad_matrix(self): """Make sure the input matrix is valid""" # should raise an exception for an empty matrix self.assertRaises(TypeError, Matrix, []) # should raise an exception for an invalid matrix self.assertRaises(TypeError, Matrix, ['a']) # should raise an exception for an incorrect matrix # must be 2-dimensional self.assertRaises(TypeError, Matrix, [1, 2]) def test_row_col_getters(self): # get row with index 1 self.assertEqual(self.m1.row(1), [3, 4]) # get col with index 1 self.assertEqual(self.m1.col(1), [2, 4]) def test_transposal(self): self.m1.transpose() self.assertEqual(self.m1.matrix, [[1, 3], [2, 4]]) def test_addition(self): # should raise an exception for addition of matrices with # different lengths self.assertRaises(IndexError, self.m1.__add__, self.m3) # test simple addition self.assertEqual((self.m1 + self.m2).matrix, [[0, 7], [3, 13]]) def test_multiplication(self): # test whether number of columns in multiplicand # is equal to number of rows in multiplier self.assertRaises(IndexError, self.m1.__mul__, self.m3) # test multiplication self.assertEqual((self.m3 * self.m4).matrix, [[13, 48], [3, 83], [2, 69]])
def test_adding_columns(self): columns = 2 rows = 3 matrix = Matrix(rows, columns) self.assertRaises(ValueError, matrix.setColumn, 1, [1, 2, 3, 4]) matrix.setColumn(1, [1, 2, 3]) matrix.setColumn(2, [4, 5, 6]) self.assertEqual(matrix.matrix, [[1, 4], [2, 5], [3, 6]]) self.assertEqual(matrix.getColumn(1), [1, 2, 3])
def test_negate(self): self.assertEqual(-self.m, self.m) m = Matrix(3, 3) m.set(0, 0, -1) m.set(1, 1, -1) m.set(2, 2, -1) self.assertEqual(-self.e, m)
def test_scale(self): m = Matrix() m = m.scale(scale_x=2, scale_y=3) expected = [[2, 0, 0], [0, 3, 0], [0, 0, 1]] self.compareMatrix(m.matrix, expected)
def otherGaussSiedelB(A,m): toReturn = Matrix(m,m) for i in range(0,m): for j in range(0,m): if i == j: toReturn.insert(i,j,(1-A.at(i,j))) else: toReturn.insert(i,j,(-A.at(i,j))) return copy.deepcopy(toReturn)
def testInvert(self): """Обращение матрицы""" # обращаем матрицу и проверяем результат a = Matrix([[1, 1], [2, 1]]) b = Matrix([[-1, 1], [2, -1]]) self.assertEqual(a.invert(), b)
def test_translate(self): m = Matrix() m = m.translate(x=4, y=-2) expected = [[1, 0, 4], [0, 1, -2], [0, 0, 1]] self.compareMatrix(m.matrix, expected)
def testTranspose(self): matrix = Matrix([1, 2], [3, 4]) self.assertEquals( Matrix([1, 3], [2, 4]), matrix.transpose()) matrix2 = Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]) self.assertEquals( Matrix([1, 4, 7], [2, 5, 8], [3, 6, 9]), matrix2.transpose())
from matrix import Matrix matrix1 = Matrix(2, 2) matrix2 = Matrix(2, 2) matrix1.insert() print(matrix1.determinant(1)) # matrix2.insert() # # print(matrix1.add(matrix2)) # print(matrix1.subtract(matrix2)) # print(matrix1.multiply(matrix2))
self.stateMatrix = self.transitionMatrix * self.stateMatrix if(self.externalMotion != None): self.stateMatrix += self.externalTransition * self.externalMotion self.updateCovariance() if __name__ == "__main__": timeStep = 1 ## stateMatrix = Matrix([[0],[0]]) ## stateErrors = Matrix([[1000, 0], [0, 1000]]) ## transitionMatrix = Matrix([[1, timeStep],[0, 1]]) ## measureMatrix = Matrix([[1, 0]]) ## measureErrors = Matrix([[1]]) ## externalTransition = Matrix([[.5 * math.pow(timeStep, 2)], [timeStep]]) ## externalMotion = Matrix([[0]]) stateMatrix = Matrix([[1],[0]]) stateErrors = Matrix([[100, 0], [0, 100]]) transitionMatrix = Matrix([[1, timeStep],[0, 1]]) measureMatrix = Matrix([[1, 0]]) measureErrors = Matrix([[200]]) externalTransition = Matrix([[.5 * math.pow(timeStep, 2)], [timeStep]]) externalMotion = Matrix([[0]]) fil = KalmanFilter(stateMatrix, stateErrors, transitionMatrix, measureMatrix, measureErrors, externalTransition, externalMotion) print(stateMatrix) print(stateErrors) print('-' * 20) print('\n') sensorNoiseMag = 1 actualStates = [x for x in range(1, 20)] #actualStates = [1 + .5 * math.pow(x, 2) for x in range(1, 20)]
def test_jacobians(): x = Matrix(3, 1, [[4.0], [7.0], [2.0]]) correct = Matrix(3, 3, [[3.0, 4.5, 11.5], [4.0, 1.5, 9], [5.0, 1, 2]]).transpose() _, jacobian = autodiff.finite_difference(func_jacobian_matmul, [x]) test_assert(correct.compare(jacobian, 1e-3)) _, jacobian, _ = autodiff.compute_gradients(func_jacobian_matmul, [x], 0, reverse_mode = True) test_assert(correct.compare(jacobian, 1e-3)) _, jacobian, _ = autodiff.compute_gradients(func_jacobian_matmul, [x], 0, reverse_mode = False) test_assert(correct.compare(jacobian, 1e-3)) correct = Matrix(1, 3, [[0, 0, 0]]) x = 2.5 _, jacobian = autodiff.finite_difference(func_jacobian_const, [x]) test_assert(correct.compare(jacobian, 1e-3)) _, jacobian, _ = autodiff.compute_gradients(func_jacobian_const, [x], 0, reverse_mode = True) test_assert(correct.compare(jacobian, 1e-3)) _, jacobian, _ = autodiff.compute_gradients(func_jacobian_const, [x], 0, reverse_mode = False) test_assert(correct.compare(jacobian, 1e-3))
def test_extract_row_where_numbers_have_different_widths(self): matrix = Matrix("1 2\n10 20") self.assertEqual(matrix.row(2), [10, 20])
class MatrixTest(unittest.TestCase): m_rows = ['catt', 'aata', 'tatc'] m_columns = ['cat', 'aaa', 'ttt', 'tac'] m_back_diagonals = ['t', 'aa', 'cat', 'atc', 'ta', 't'] m_forw_diagonals = ['c', 'at', 'tta', 'tat', 'aa', 'c'] def setUp(self): self.matrix = Matrix(3, 4) for i, values in enumerate(self.m_rows): self.matrix.fillRow(i, list(values)) def test_initError(self): with self.assertRaisesRegex(ValueError, 'rows must be greater than or equal to 2'): Matrix(1, 3) with self.assertRaisesRegex(ValueError, 'cols must be greater than or equal to 2'): Matrix(3, 1) def test_numRows(self): self.assertEqual(3, self.matrix.numRows) def test_numColumns(self): self.assertEqual(4, self.matrix.numColumns) def test_get(self): self.assertEqual(self.matrix.get(0, 0), 'c') self.assertEqual(self.matrix.get(2, 4), None) def test_set(self): self.matrix.set(0, 0, 'z') self.assertEqual(self.matrix.get(0, 0), 'z') def test_getRows(self): rows = [list(r) for r in self.m_rows] self.assertEqual(rows, self.matrix.getRows()) def test_getColumns(self): cols = [list(c) for c in self.m_columns] self.assertEqual(cols, self.matrix.getColumns()) def test_getRow(self): self.assertEqual(self.matrix.getRow(0), list(self.m_rows[0])) def test_getColumn(self): self.assertEqual(self.matrix.getColumn(2), list(self.m_columns[2])) def test_fillRow(self): row = ['a', 'b', 'c', 'd'] self.matrix.fillRow(0, row) self.assertEqual(self.matrix.getRow(0), row) def test_fillColumn(self): col = ['a', 'b', 'c'] self.matrix.fillColumn(0, col) self.assertEqual(self.matrix.getColumn(0), col) def test_getDiagonal_forward(self): pass def test_getDiagonal_backward(self): pass def test_getDiagonals_forward(self): diagonals = [list(x) for x in self.m_forw_diagonals] self.assertEqual(sorted(diagonals), sorted(self.matrix.getDiagonals(forward=True))) def test_getDiagonals_backward(self): diagonals = [list(x) for x in self.m_back_diagonals] self.assertEqual(sorted(diagonals), sorted(self.matrix.getDiagonals()))
def main(): m2x2 = Matrix(-2, 1, 0, -2) print(m2x2) print(m2x2[0, 0]) m2x2[1, 0] = 3 print(m2x2) m1 = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9) m2 = Matrix(9, 8, 7, 6, 5, 4, 3, 2, 1) print(m1) m5x5 = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25) print(m5x5) print(m1.matrixSum(m2)) print(m1.matrixAddScalar(10)) print(m1.matrixMuliplayScalar(3)) print(m1.matrixMultiplayCorrespondingElements(m2)) print(m1.matrixProduct(m2)) print(m2x2.getDeterminant()) print(m1.getDeterminant()) print(m5x5.getDeterminant())
def generate_graph(nodes, density, mode, directed, force=settings.force): """ graph generated via algorithm: 1. calculate edge count 2. build a tree 3. add random edges to meet edge count """ connected = [] disconnected = [i for i in range(nodes)] if directed: # calculate edge count based on node count and density edge_list = [(x, y) for x in range(nodes) for y in range(nodes) if x != y] edges = nodes * (nodes - 1) * density if edges < nodes - 1 and not force: print( "Minimum graph density for this problem is {:2.0%}. " "To generate less dense graph anyway, set argument force to True." .format(float(1 / nodes)), file=sys.stderr) edges = nodes - 1 else: edge_list = [(x, y) for x in range(nodes) for y in range(nodes) if x != y] edges = nodes * (nodes - 1) * density / 2 if edges < nodes - 1 and not force: print( "Minimum graph density for this problem is {:2.0%}. " "To generate less dense graph anyway, set argument force to True." .format(float(2 / nodes)), file=sys.stderr) edges = nodes - 1 bar = ProgBar(edges, title='Generating graph', stream=sys.stdout) if mode == 'list': graph = ListGraph(nodes) while len(disconnected) > 0: # build a tree if len(connected) == 0: s = randint(nodes) e = randint(nodes) connected.append(s) disconnected.remove(s) else: s = connected[randint( len(connected) )] # get starting vertex randomly from already connected nodes e = disconnected[randint( len(disconnected) )] # get ending vertex randomly from not yet connected disconnected.remove(e) w = randint(1, nodes) graph.add_connection(s, e, w) # add connection if not directed: graph.add_connection(e, s, w) connected.append(e) edge_list.remove((s, e)) # remove edge from the pool if not directed: edge_list.remove((e, s)) edges -= 1 bar.update() while edges > 0: # add remaining edges at random s, e = edge_list[randint(len(edge_list))] edge_list.remove((s, e)) w = randint(nodes) graph.add_connection(s, e, w) if not directed: edge_list.remove((e, s)) graph.add_connection(e, s, w) edges -= 1 bar.update() elif mode == 'matrix': graph = Matrix(nodes) while len(disconnected) > 0: # build a tree if len(connected) == 0: s = randint(nodes) e = randint(nodes) connected.append(s) disconnected.remove(s) else: s = connected[randint( len(connected) )] # get starting vertex randomly from already connected nodes e = disconnected[randint( len(disconnected) )] # get ending vertex randomly from not yet connected disconnected.remove(e) w = randint(1, nodes) graph.set(s, e, w) # add connection if not directed: graph.set(e, s, w) connected.append(e) edge_list.remove((s, e)) # remove edge from the pool if not directed: edge_list.remove((e, s)) edges -= 1 bar.update() bar = ProgBar(20, stream=sys.stdout) while edges > 0: # add remaining edges at random s, e = edge_list[randint(len(edge_list))] edge_list.remove((s, e)) w = randint(nodes) graph.set(s, e, w) if not directed: edge_list.remove((e, s)) graph.set(e, s, w) edges -= 1 bar.update() print("Generated graph") return graph
def test_extract_row_from_one_number_matrix(self): matrix = Matrix("1") self.assertEqual(matrix.row(1), [1])
def test_can_extract_column(self): matrix = Matrix("1 2 3\n4 5 6\n7 8 9") self.assertEqual(matrix.column(3), [3, 6, 9])
def func_gradient_dot(x): p = Matrix(3, 1, [[3.0], [4.0], [5.0]]) return x.transpose().matmul(p)
def test_can_extract_row_from_non_square_matrix(self): matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n8 7 6") self.assertEqual(matrix.row(3), [7, 8, 9])
class MainForm: def __init__(self): self.root = Tk() self.root.title("Plot") self.root.attributes("-zoomed", True) self.title = "Calculus" ################################################################# # User congfig area ################################################################# # Global config self.getVectorMethod = "Gaussian" self.getMcLaurinSeriesMethod = "Analytically" # Justify the plot self.left = -50 self.right = 50 self.seq = 1000 self.thresshole = 500 ################################################################# # End user config area ################################################################# # Plot function self.parse = None self.option = "root" self.inputChanged = False # Get root information self.root.update() self.width = self.root.winfo_width() self.height = self.root.winfo_height() self.__DPI = 110.0 # Average DPI for most monitor self.root.geometry("{}x{}".format(self.width, self.height)) # Matrix self.matrix = Matrix() self.saveSetPoint = False # Loading GUI self.GUI() # Event Handler self.state = False self.root.bind("<F11>", self.toggle_fullscreen) self.root.bind("<Escape>", self.end_fullscreen) def graph(self): self.parse_func() # Root f = open("calculus.dot", 'w+') f.write("graph " + self.title + " {\n") f.write('\tnode [ fontname = "Arial"]\n') self.parse.root.toGraph(-1, f) f.write('}') f.close() G = AGraph("calculus.dot") G.draw("calculus.png", prog='dot') # Derivative analyticaly f = open("derivative.dot", 'w+') f.write("graph derivative {\n") f.write('\tnode [ fontname = "Arial"]\n') if (self.parse.derivative != None): self.parse.derivative.toGraph(-1, f) f.write('}') f.close() G = AGraph("derivative.dot") G.draw("derivative.png", prog='dot') messagebox.showinfo("Info", "Success") def plot(self): self.parse_func() # Plot self.a.set_title(self.title, fontsize=16) if (self.option == "root"): t = numpy.linspace( self.left, self.right, (numpy.abs(self.right) + numpy.abs(self.left)) * self.seq + 1) self.a.plot(t, self.function(t, self.parse.function, h=0.0000000001), color='red') title = self.parse.str_function elif (self.option == "da"): t = numpy.linspace( self.left, self.right, (numpy.abs(self.right) + numpy.abs(self.left)) * self.seq + 1) self.a.plot(t, self.function(t, self.parse.function_da, h=0.0000000001), color='blue') title = self.parse.str_function_da elif (self.option == "dq"): t = numpy.linspace( self.left, self.right, (numpy.abs(self.right) + numpy.abs(self.left)) * self.seq + 1) self.a.plot(t, self.function(t, self.parse.function_dq, h=0.0000000001), color='orange') title = self.parse.str_function_dq elif (self.option == "fill"): t = numpy.linspace( int(self.left_bound.get()), int(self.right_bound.get()), (numpy.abs(int(self.left_bound.get())) + numpy.abs(int(self.right_bound.get()))) * self.seq + 1) self.a.fill_between(t, 0, self.function(t, self.parse.function), color="green") title = "Area: {}".format(self.lbl_riemann) elif (self.option == "McLaurin"): vector = self.getMcLaurinVector( 0, depth=int(self.depth_input.get()), method=self.getMcLaurinSeriesMethod) mclaurrin = "{}".format(vector[0]) for i in range(1, len(vector)): mclaurrin += "+{}*x^{}".format(vector[i], i) t = numpy.linspace( self.left, self.right, (numpy.abs(self.right) + numpy.abs(self.left)) * self.seq + 1) y = numpy.zeros(len(t)) # allocate y with float elements for i in range(len(t)): try: y[i] = vector[0] for j in range(1, len(vector)): y[i] += vector[j] * t[i]**j except Exception as ex: y[i] = numpy.NAN self.a.plot(t, y, color='yellow') title = mclaurrin self.a.set_title(title, fontsize=8) self.canvas.draw() def parse_func(self): if (self.inputChanged): try: print(self.input.get()) self.parse = Parse(self.input.get().replace(" ", "")) except Exception as e: messagebox.showerror( "Error", "Somethings gone wrong, please check your input again") print(e) return self.lbl_function.set(self.parse.str_function) self.lbl_derivative.set(self.parse.str_function_da) self.lbl_derivative_dq.set(self.parse.str_function_dq) try: self.lbl_riemann.set( self.parse.getRiemannIntegrals( float(self.left_bound.get()), float(self.right_bound.get()))) except Exception as e: messagebox.showerror( "Error", "Somethings gone wrong, please check your input again") print(e) return self.inputChanged = False def function(self, t, str_func, h=0.0000000001): y = numpy.zeros(len(t)) # allocate y with float elements for i in range(len(t)): x = t[i] try: y[i] = eval(str_func) if (abs(y[i]) > self.thresshole): y[i] = numpy.NAN pass except Exception as ex: print(ex) y[i] = numpy.NAN return y def clearPlot(self): self.a.clear() self.a.grid(True) self.a.set_title("Calculus", fontsize=16) self.canvas.draw() def setPlotFunction(self, option="linear", func="0"): self.option = option def getMcLaurinSeries(self, x, x0, depth=1, h=0.000001): S = eval(self.parse.function) for i in range(1, depth): S += (self.parse.getDifferenceQuotion(x, depth=i, h=h) * ((x0 - x)**i)) / numpy.math.factorial(i) return S def getMcLaurinVector(self, x, depth=1, method="Newton"): depth += 1 if (method == "Newton"): vector = [] try: vector.append(eval(self.parse.function)) except Exception as ex: messagebox.showerror( "Error!", "Invalid function. Please check your input again!") print(ex) return [] for i in range(1, depth): try: vector.append( self.parse.getDifferenceQuotion(x, depth=i) / numpy.math.factorial(i)) except Exception as ex: messagebox.showerror( "Error!", "Invalid derivative at depth {}. Please try other function!" .format({i})) print(ex) return [] return vector elif (method == "Analytically"): vector = [] derivative = self.parse.root try: vector.append(eval(derivative.toFunction())) except Exception as ex: messagebox.showerror( "Error!", "Invalid function. Please check your input again!") print(ex) return [] for i in range(1, depth): derivative = derivative.getDerivative() derivative = derivative.simplify( ) if derivative != None else notation.Number(data="0") try: vector.append( eval(derivative.toFunction()) / numpy.math.factorial(i)) except Exception as ex: messagebox.showerror( "Error!", "Invalid derivative at depth {}. Please try other function!" .format({i})) print(ex) return [] return vector return [] def setRecordSetpointMode(self, option=False): self.saveSetPoint = option if (option == False): if (self.matrix.setPointLen == 0): messagebox.showerror("Set point is empty") return # Plot v = self.matrix.getVector(method=self.getVectorMethod) if (v == []): messagebox.showerror("Error", "Your setpoints is not continuos") self.matrix.refresh() return t = numpy.linspace( self.left, self.right, (numpy.abs(self.right) + numpy.abs(self.left)) * self.seq + 1) y = numpy.zeros(len(t)) # allocate y with float elements for i in range(len(t)): for j in range(len(v)): y[i] += v[j] * (t[i]**j) self.lbl_recordSetpoint.set("Setpoint record tunred off") poly = "{:.4f}".format(round(v[0], 4)) if (self.matrix.setPointLen >= 2): poly += " + {:.4f}*x".format(round(v[1], 4)) for i in range(2, self.matrix.setPointLen): poly += " + {:.4f}*x^{}".format(round(v[i], 4), i) if (i % 4 == 0): poly += "\n" self.a.set_title(poly, fontsize=8) self.matrix.refresh() self.a.plot(t, y, color='blue') self.canvas.draw() else: self.lbl_recordSetpoint.set("Setpoint record tunred on") def showSetPoint(self): points = self.matrix.setPoint message = "x\ty\n" for tmpMsg in points: message += "{:.4f}\t{:.4f}\n".format(tmpMsg[0], tmpMsg[1]) messagebox.showinfo("Setpoint", message) def showPicture(self, imgDir=None): self.parse_func() if (imgDir != None): img = mpimg.imread(imgDir) else: url = "https://www.graphsketch.com/render.php?\ eqn1_color=1&\ eqn1_eqn={}&\ x_min={}&x_max={}&\ y_min={}&y_max={}&\ x_tick=1&y_tick=1&\ x_label_freq=5&\ y_label_freq=5&\ do_grid=0&\ do_grid=1&\ bold_labeled_lines=0&\ bold_labeled_lines=1&\ line_width=4&\ image_w=850&\ image_h=525".format(self.parse.str_function, self.left, self.right, self.left, self.right).replace(" ", "") try: urlretrieve(url, filename="tmp.png") img = mpimg.imread('tmp.png') os.remove("tmp.png") except Exception as e: messagebox.showerror( "Error", "Somethings gone wrong, please try again later") print(e) return open_new_tab(url.replace("render.php?", "?")) plt.imshow(img) plt.show() def GUI(self): # ========================================================================== # Top Frame # ========================================================================== self.bottomFrame = Frame(self.root, width=self.width, bd=2, relief="raise") self.bottomFrame.pack(side=TOP, fill=BOTH, expand=True) """ Ploting """ # Figure fig = Figure(figsize=(self.width / self.__DPI, self.height / self.__DPI - 1)) self.a = fig.add_subplot(111) self.a.set_title("Calculus", fontsize=16) self.a.set_ylabel("Y", fontsize=14) self.a.set_xlabel("X", fontsize=14) self.a.axhline(linewidth=1, color='black') self.a.axvline(linewidth=1, color='black') self.a.plot([], [], color='red') self.a.grid(True) self.canvas = FigureCanvasTkAgg(fig, master=self.bottomFrame) self.canvas.draw() self.canvas.get_tk_widget().pack(pady=5) # Toolbar self.toolbar = NavigationToolbar2Tk(self.canvas, self.bottomFrame) self.toolbar.update() self.canvas.get_tk_widget().pack() # ========================================================================== # Bottom Frame # ========================================================================== self.topFrame = Frame(self.root, width=self.width, bd=2, relief="raise") self.topFrame.pack(side=TOP, fill=BOTH, expand=True) """ Top Left """ self.topFrameLeft = Frame(self.topFrame, width=self.width / 2) self.topFrameLeft.pack(side=LEFT, expand=True) ### Left self.frameLeft_Lpanel = Frame(self.topFrameLeft) self.frameLeft_Lpanel.pack(side=LEFT, expand=True) self.frameLeft_Lpanel.grid_propagate(1) # Label self.lbl_function = StringVar() self.lbl_function.set("None") self.lbl_derivative = StringVar() self.lbl_derivative.set("None") self.lbl_derivative_dq = StringVar() self.lbl_derivative_dq.set("None") self.lbl_riemann = StringVar() self.lbl_riemann.set("None") Label(self.frameLeft_Lpanel, text="Input").grid(row=0, column=0, sticky=W, padx=2) Label(self.frameLeft_Lpanel, text="Function:").grid(row=1, column=0, sticky=W, padx=2) Label(self.frameLeft_Lpanel, textvariable=self.lbl_function, width=60).grid(row=1, column=1, columnspan=2, sticky=W, padx=2) Label(self.frameLeft_Lpanel, text="Derivative:").grid(row=2, column=0, sticky=W, padx=2) Label(self.frameLeft_Lpanel, textvariable=self.lbl_derivative, width=60).grid(row=2, column=1, columnspan=2, sticky=W, padx=2) Label(self.frameLeft_Lpanel, text="Difference quotion:").grid(row=3, column=0, sticky=W, padx=2) Label(self.frameLeft_Lpanel, textvariable=self.lbl_derivative_dq, width=60).grid(row=3, column=1, columnspan=2, sticky=W, padx=2) Label(self.frameLeft_Lpanel, text="Riemann quotion:").grid(row=4, column=0, sticky=W, padx=2) Label(self.frameLeft_Lpanel, textvariable=self.lbl_riemann, width=60).grid(row=4, column=1, columnspan=2, sticky=W, padx=2) # Input field self.input = Entry(self.frameLeft_Lpanel, width=30) self.input.grid(row=0, column=1, sticky=W, padx=2) self.input.bind("<Button-1>", self.input_changed) # Button Button(self.frameLeft_Lpanel, text="Parse", command=self.parse_func).grid(row=0, column=2, sticky=W, padx=2) ###Right self.frameLeft_Rpanel = Frame(self.topFrameLeft) self.frameLeft_Rpanel.pack(side=LEFT, expand=True) # Label self.lbl_recordSetpoint = StringVar() self.lbl_recordSetpoint.set("Off") Label(self.frameLeft_Rpanel, text="Polynomio").grid(row=0, column=0, columnspan=1, sticky=W, padx=2) Label(self.frameLeft_Rpanel, textvariable=self.lbl_recordSetpoint).grid(row=0, column=1, columnspan=2, sticky=W, padx=2) self.lbl_polynomial = StringVar() self.lbl_polynomial.set("") Label(self.frameLeft_Rpanel, textvariable=self.lbl_polynomial).grid(row=2, column=0, columnspan=3, sticky=W, padx=2) # Button Button(self.frameLeft_Rpanel, text="Show setpoint", command=self.showSetPoint).grid(row=1, column=0, padx=2) Button(self.frameLeft_Rpanel, text="Record setpoint", command=lambda: self.setRecordSetpointMode(option=True)).grid( row=1, column=1, padx=2) Button(self.frameLeft_Rpanel, text="Get polynomial", command=lambda: self.setRecordSetpointMode(option=False)).grid( row=1, column=2, padx=2) """ Top Right """ self.topFrameRight = Frame(self.topFrame, width=self.width / 2) self.topFrameRight.pack(side=LEFT, expand=True) ### Right self.frameRightOption = Frame(self.topFrameRight) self.frameRightOption.pack(side=LEFT, expand=True) #Button Button(self.frameRightOption, text="Plot", command=self.plot).grid(row=0, column=0, columnspan=1, rowspan=5, padx=2) # Input self.left_bound = Entry(self.frameRightOption, width=5) self.left_bound.insert(0, self.left) self.left_bound.grid(row=3, column=2, sticky=W, padx=2) self.right_bound = Entry(self.frameRightOption, width=5) self.right_bound.insert(0, self.right) self.right_bound.grid(row=3, column=3, sticky=W, padx=2) self.a_input = Entry(self.frameRightOption, width=5) self.a_input.insert(0, "0") self.a_input.grid(row=4, column=2, sticky=W, padx=2) self.depth_input = Entry(self.frameRightOption, width=5) self.depth_input.insert(0, "8") self.depth_input.grid(row=4, column=3, sticky=W, padx=2) # Ratio button v = IntVar() Radiobutton(self.frameRightOption, text="Parsed function", padx=2, pady=2, command=lambda: self.setPlotFunction(option="root"), variable=v, value=0).grid(row=0, column=1, padx=2, sticky=W) Radiobutton(self.frameRightOption, text="Function derivative", padx=2, pady=2, command=lambda: self.setPlotFunction(option="da"), variable=v, value=1).grid(row=1, column=1, padx=2, sticky=W) Radiobutton(self.frameRightOption, text="Function diferrence quotion", padx=2, pady=2, command=lambda: self.setPlotFunction(option="dq"), variable=v, value=2).grid(row=2, column=1, padx=2, sticky=W) Radiobutton(self.frameRightOption, text="Riemann integrals", padx=2, pady=2, command=lambda: self.setPlotFunction(option="fill"), variable=v, value=3).grid(row=3, column=1, padx=2, sticky=W) Radiobutton(self.frameRightOption, text="Mc Laurin series", padx=2, pady=2, command=lambda: self.setPlotFunction(option="McLaurin"), variable=v, value=4).grid(row=4, column=1, padx=2, sticky=W) ### Left self.frameRightButton = Frame(self.topFrameRight) self.frameRightButton.pack(side=LEFT, expand=True, padx=50) # Button Button(self.frameRightButton, text="Export Graph", command=self.graph, width=12).grid(row=0, column=0, padx=2, sticky=E) Button(self.frameRightButton, text="Clean Canvas", command=self.clearPlot, width=12).grid(row=1, column=0, padx=2, sticky=E) Button(self.frameRightButton, text="Validate", command=self.showPicture, width=12).grid(row=2, column=0, padx=2, sticky=E) #region Event def input_changed(self, event): self.inputChanged = True def canvas_on_key_hover(self, event): key_press_handler(event, self.canvas, self.toolbar) def canvas_on_click(self, event): if (self.saveSetPoint == True): self.matrix.addSetPoint(float(event.xdata), float(event.ydata)) self.a.plot(event.xdata, event.ydata, 'rs', color="black") self.canvas.draw() def toggle_fullscreen(self, event=None): self.state = not self.state # Just toggling the boolean self.root.attributes("-fullscreen", self.state) return "break" def end_fullscreen(self, event=None): self.state = False self.root.attributes("-fullscreen", False) return "break"
def load_graph(path, mode, directed): f = open(path, 'r+') for line in f.readlines(): vals = [int(val) for val in line.split(' ')] if len(vals) == 2: if mode == 'matrix': graph = Matrix(vals[1]) else: graph = ListGraph(vals[1]) else: if mode == 'matrix': graph.set(vals[0], vals[1], vals[2]) if directed and graph.get(vals[1], vals[0]) == 0: graph.set(vals[1], vals[0], -1) else: graph.set(vals[1], vals[0], vals[2]) else: graph.add_connection(vals[0], vals[1], vals[2]) if not directed: graph.add_connection(vals[1], vals[0], vals[2]) return graph
# Content-based recommendation from matrix import Matrix import numpy # numpy.set_printoptions(precision=2) #------------------------------------------------------------------- UF = Matrix( 'UserFeature', ['Mary', 'Tom', 'Jerry'], ['J.Roberts', 'T.Hanks', 'TheRock', 'Thriller', 'Action', 'Romantics']) UF.set(0, [5, 4, 1, 0, 0, 4]) UF.set(1, [3, 4, 0, 0, 0, 5]) UF.set(2, [1, 1, 5, 4, 5, 2]) UF.show() IF = Matrix( 'ItemFeature', ['LarryCrowne', 'PrettyWoman', 'Sully', 'Hercules'], ['J.Roberts', 'T.Hanks', 'TheRock', 'Thriller', 'Action', 'Romantics']) IF.set(0, [1, 1, 0, 0, 0, 1]) IF.set(1, [1, 1, 0, 0, 0, 1]) IF.set(2, [0, 1, 0, 1, 1, 0]) IF.set(3, [0, 0, 1, 1, 1, 0]) IF.show() UI = numpy.matmul(UF.mat, numpy.transpose(UF.mat)) print(UI)
def generate_graph_nx( nodes: int, density, mode, directed, force=settings.force): # graph generation using networkx bar = ProgBar(20, title='Generating graph', stream=sys.stdout) if directed: # calculate edge count based on node count and density edges = nodes * (nodes - 1) * density if edges < nodes - 1 and not force: print( "Minimum graph density for this problem is {:2.0%}. " "To generate less dense graph anyway, set argument force to True." .format(float(1 / nodes)), file=sys.stderr) edges = nodes - 1 else: edges = nodes * (nodes - 1) * density / 2 if edges < nodes - 1 and not force: print( "Minimum graph density for this problem is {:2.0%}. " "To generate less dense graph anyway, set argument force to True." .format(float(2 / nodes)), file=sys.stderr) edges = nodes - 1 bar.update() G = nx.generators.random_graphs.gnm_random_graph( nodes, edges, directed=directed) # generate random graph bar.update() if not directed: # check connectivity and generate new graph if failed while not nx.is_connected(G): G = nx.generators.random_graphs.gnm_random_graph( nodes, edges, directed=directed) else: cont = False while not cont: cont = True for node in G.nodes: if len([x for x in G.neighbors(node)]) == 0: cont = False G = nx.generators.random_graphs.gnm_random_graph( nodes, edges, directed=directed) break bar.update() if mode == 'matrix': # convert generated networkx graph to own structure ret = Matrix(nodes) for x, y in G.edges: w = randint(1, nodes) ret.set(x, y, w) if directed and ret.get(y, x) == 0: ret.set(y, x, 0) else: ret.set(y, x, w) bar.update() return ret else: ret = ListGraph(nodes) for x, y in G.edges: w = randint(1, nodes) ret.add_connection(x, y, w) if not directed: ret.add_connection(y, x, w) bar.update() return ret
def translation(mat, i, j): print(f"Translation along vector ({i}, {j})") matrix_transformation = Matrix.identity(3) matrix_transformation[1, 3] = i matrix_transformation[2, 3] = j return matrix_transformation * mat
def setUp(self): self.matrix = Matrix(3, 4) for i, values in enumerate(self.m_rows): self.matrix.fillRow(i, list(values))
def func_jacobian_matmul(x): p = Matrix(3, 3, [[3.0, 4.5, 11.5], [4.0, 1.5, 9], [5.0, 1, 2]]) return p.matmul(x)
from matrix import Matrix ##TESTING GROUNDS FOR EXPERIMENTAL CODE def assertion(function,input,result): assert function(input).round() == result,('\nError, Output:',function(input),'Did not Match Result:',result) print('\nPassed') bruh = Matrix(elements = [[6,2],[3,2]]) breh = Matrix(elements = [[3,2],[5,6]]) bruh = Matrix(elements = [[3,7,11],[28,31,12],[11,11,43]]) tester = Matrix(elements = [[3,0,0],[0,3,0],[0,0,3]]) new_bruh = Matrix(elements = [[7,22,13],[12,4,4],[0,8,8]]) ID = Matrix(shape = (3,3),fill = 'diag') matrices = [bruh,tester,new_bruh] for i in range(len(matrices)): print('\nInverse Test:',i+1) matrix = matrices[i] assertion(matrix.matrix_mult,matrix.inverse(),ID) print('\nInverse By Minors Test:',i+1) matrix = matrices[i] assertion(matrix.matrix_mult,matrix.inverse_by_minors(),ID)
def test_can_extract_row(self): matrix = Matrix("1 2\n3 4") self.assertEqual(matrix.row(2), [3, 4])
def func_gradient_scalarmul(x): z = (12 * x).reduce_sum() return Matrix(1,1,[[z]])
def func_gradient_hadamard(x): p = Matrix(3, 1, [[3.0], [4.0], [5.0]]) z = (x * p).reduce_sum() return Matrix(1,1,[[z]])
def func_gradient_square(x): z = (x * x).reduce_sum() return Matrix(1,1,[[z]])
def func_jacobian_const(x): return Matrix(3, 1, [[3.0], [4.5], [11.5]]) + x - x
from matrix import Matrix mat_sum = Matrix(1000, 10) mat_sum.load_from_file("data/sum_test.csv") print(mat_sum.sum_range(0, 3, 150, 8))
# Run the MATRIX display from matrix import Matrix if __name__ == "__main__": matrix = Matrix() matrix.main_loop()
def test_can_extract_column_from_non_square_matrix(self): matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n8 7 6") self.assertEqual(matrix.column(3), [3, 6, 9, 6])
def func_gradient_matmul(x): p = Matrix(3, 1, [[3.0], [4.0], [5.0]]) z = x.matmul(p.transpose()).reduce_sum() return Matrix(1,1,[[z]])
def test_extract_column_from_one_number_matrix(self): matrix = Matrix("1") self.assertEqual(matrix.column(1), [1])
def test_extract_column_where_numbers_have_different_widths(self): matrix = Matrix("89 1903 3\n18 3 1\n9 4 800") self.assertEqual(matrix.column(2), [1903, 3, 4])