def read_city_graph(filename): f = open(filename) g = WeightedGraph() global vertices vertices = {} global edges edges = {} line = f.readline() while line: fields = line.split(",") if fields[0] == "V": v = int(fields[1]) lat = float(fields[2]) lon = float(fields[3]) g.add_vertex(v) vertices[v] = (int(lat * 100000), int(lon * 100000) ) elif fields[0] == "E": e = (int(fields[1]), int(fields[2])) g.add_edge(int(fields[1]),int(fields[2])) edges[e] = {"street": fields[3]} line = f.readline() return g
def read_weighted_graph_file(path): lines = [ [ tuple.split(",") for tuple in line.split() ] \ for line in open(path).readlines() ] graph = WeightedGraph(len(lines)) for line in lines: v = int(line[0][0]) - 1 for edge in line[1:]: w = int(edge[0]) - 1 cost = int(edge[1]) graph.add_edge(v, w, cost) return graph
def run_tournament(game: PDGame) -> None: """Run a tournament between all strategies. If <show_heatmap> is set, then display a heatmap that shows the match-ups between the strategies. """ all_strategies = get_all_strategies() graph = WeightedGraph() for s1 in all_strategies: for s2 in all_strategies: new_game = PDGame(game.num_rounds) strategy1 = s1.__copy__() strategy2 = s2.__copy__() player1 = Player(strategy1, 1) player2 = Player(strategy2, 2) if isinstance(player1.strategy, LearningStrategy): player1 = get_trained_learner(player2, game.num_rounds) graph.add_vertex(player1.strategy.name) graph.add_vertex(player2.strategy.name) run_game(new_game, player1, player2) if strategy1.name == 'Learning Strategy' and strategy2.name == 'Learning Strategy': player1.curr_points, player2.curr_points = 0, 0 graph.add_edge((player1.strategy.name, player1.curr_points), (player2.strategy.name, player2.curr_points)) display_heatmap(graph)
def __init__(self): super().__init__() self.setWindowTitle("Pathfinding Algorithm Visualizer") self.layout = QVBoxLayout() columns = 40 rows = 30 self.graph = WeightedGraph(columns, rows) self.grid_ui = GridUI(self.graph, columns, rows) self.grid_ui.setContentsMargins(0, 0, 0, 0) self.grid_ui.setStyleSheet('background-color: white;') self.buttons_layout = QHBoxLayout() self.start_button = QPushButton('Start') self.reset_button = QPushButton('Reset grid') self.path_button = QPushButton('Clear path') self.change_button = QPushButton('Change parameters') self.buttons_layout.addWidget(self.start_button) self.buttons_layout.addWidget(self.reset_button) self.buttons_layout.addWidget(self.path_button) self.buttons_layout.addWidget(self.change_button) self.layout.addWidget(self.grid_ui) self.layout.addLayout(self.buttons_layout) self.widget = QWidget() self.widget.setLayout(self.layout) self.setCentralWidget(self.widget) self.reset_button.clicked.connect(self.clear_grid) self.change_button.clicked.connect(self.show_parameter_popup) self.start_button.clicked.connect(self.generate_path) self.path_button.clicked.connect(self.clear_path) self.parameters = ParametersPopup() self.parameters.buttonBox.accepted.connect( self.update_graph_with_parameters) self.ui_thread = QThread() self.ui_thread.start() self.ui_QObj = UIQObj() self.ui_QObj.moveToThread(self.ui_thread) self.ui_QObj.update.connect(self.handle_ui_update) self.ui_QObj.start.connect(self.ui_QObj.run) self.ui_QObj.start.emit() self.path_thread = QThread() self.path_thread.start() self.path_QObj = PathQObj() self.path_QObj.moveToThread(self.path_thread) self.path_QObj.start.connect(self.path_QObj.run)
def test_weighted_graph(): g = WeightedGraph() g.insert_edge("a", {(9, "b"), (6, "c"), (1, "d")}) assert g.get_neighbors("a") == {(9, "b"), (6, "c"), (1, "d")} assert g.get_neighbors("b") == {(9, "a")} assert g.get_neighbors("c") == {(6, "a")} assert g.get_neighbors("d") == {(1, "a")} assert g.get_weight("a", "b") == 9 assert g.get_weight("a", "c") == 6 assert g.get_weight("a", "d") == 1
def read_city_graph(filename): f = open(filename) g = WeightedGraph() global vertecies vertecies = {} global edges edges = {} line = f.readline() while line: fields = line.split(",") if fields[0] == "V": v = int(fields[1]) lat = float(fields[2]) lon = float(fields[3]) g.add_vertex(v) vertecies[v] = (int(lat * 100000), int(lon * 100000)) elif fields[0] == "E": e = (int(fields[1]), int(fields[2])) g.add_edge(int(fields[1]), int(fields[2])) edges[e] = {"street": fields[3]} line = f.readline() return g
def read_city_graph(filename): #set the three variables we are gonna output EdGraph = WeightedGraph() roadNames = [] locations = {} """ Goes through each line of the file and creates a vertice or an edge """ with open(filename,"r",) as file: for line in file: line = line.split(",") if line[0] == "V": EdGraph.add_vertex(int(line[1])) #appends the information we need about the vertice locations[int(line[1])] = [int(float(line[2])*100000),int(float(line[3])*100000)] elif line[0] == "E": EdGraph.add_edge(int(line[1]), int(line[2]), cost_distance(locations[int(line[1])], locations[int(line[2])])) roadNames.append([int(line[1]), int(line[2]), line[3].strip()]) return EdGraph, roadNames, locations
def constrained_voronoi(self, seed): """Voronoi parcellation of the field starting from the input seed Parameters ---------- seed: int array of shape(p), the input seeds Returns ------- label: The resulting labelling of the data Fixme ----- deal with graphs with several ccs """ if np.size(self.field) == 0: raise ValueError('No field has been defined so far') seed = seed.astype(np.int) weights = np.sqrt(np.sum((self.field[self.edges.T[0]] - self.field[self.edges.T[1]]) ** 2, 1)) g = WeightedGraph(self.V, self.edges, weights) label = g.voronoi_labelling(seed) return label
def dijkstra(g: WeightedGraph, s: list): dist = {} pred = {} Q = PriorityQueue() def relax(u, v): if dist[v] > dist[u] + g.get_weight(u, v): dist[v] = dist[u] + g.get_weight(u, v) pred[v] = u while not Q.empty(): u = Q.get() s.append(u) for v in g.get_neighbors(u): relax(u, v)
def __init__(self): self.g, self.coord = graph_build() self.route_graph = WeightedGraph() self.s_name_text = "" self.d_name_text = "" self.new_path = False self.address_q = Queue() self.waypoints = [] self.sd_dict = dict() self.path_dict = dict() self.name_vert_dict = dict() self.sd_list = set() self.ordered_list = [] self.master_path = []
def main(): with open(sys.argv[1]) as f: lines = f.read().splitlines() adj = [] for line in lines: row = [] for node in line.split(','): if node == '-': row.append(None) else: row.append(int(node)) adj.append(row) num_nodes = len(adj) # make sure the adjacency matrix is square assert all(len(row) == num_nodes for row in adj) graph = WeightedGraph() for i in range(num_nodes): graph.add_node(i) for x, row in enumerate(adj): for y, weight in enumerate(row): if weight is not None: graph.add_arc(x, y, weight) mst = min_spanning_tree(graph) # Now we want to consider half of the adjacency matrix, so we can # sum the total weight of all arcs. half_adj = [] for i, row in enumerate(adj): new_row = [] for j, weight in enumerate(row): if i <= j: new_row.append(weight) else: new_row.append(None) half_adj.append(new_row) # Now remove all of the arcs in the mst, so the arcs we are left # with are the ones that we are able to remove. for mst_arc_source, mst_arc_target in mst: half_adj[mst_arc_source][mst_arc_target] = None half_adj[mst_arc_target][mst_arc_source] = None print(sum(sum(filter(None, row)) for row in half_adj))
def kruskal_algo(graph): ds = DisjointSet() result = [] edges = graph.get_edges() map(ds.make_set, graph.get_vertex()) for edge, _ in (x for x in sorted(edges.items(), key=lambda (key, value): value)): node1 = ds.find_set(edge[0]) node2 = ds.find_set(edge[1]) if node1 == node2: continue else: result.append("{0}{1}".format(*edge)) ds.union(*edge) return result if __name__ == "__main__": graph = WeightedGraph(directed=False) graph.add_edge('A', 'B', 3) graph.add_edge('A', 'D', 1) graph.add_edge('B', 'C', 1) graph.add_edge('B', 'D', 3) graph.add_edge('C', 'D', 1) graph.add_edge('C', 'E', 5) graph.add_edge('C', 'F', 4) graph.add_edge('D', 'E', 6) graph.add_edge('F', 'E', 2) print kruskal_algo(graph)
path[source_vertex] = 0 hm = HeapMap(data=min_heap_dic) while not hm.is_empty_heap(): hm.build_min_heapify() vertex, value = hm.pop_min_element() distance[vertex] = value for edge in graph[vertex]: if edge in min_heap_dic and graph[vertex][edge] + distance.get(vertex, 0) < min_heap_dic[edge]: min_heap_dic[edge] = graph[vertex][edge] + distance.get(vertex, 0) path[edge] = vertex return path, distance if __name__ == "__main__": graph = WeightedGraph(directed=False) graph.add_edge(0, 1, 4) graph.add_edge(0, 7, 8) graph.add_edge(1, 2, 8) graph.add_edge(1, 7, 11) graph.add_edge(2, 3, 7) graph.add_edge(2, 8, 2) graph.add_edge(2, 5, 4) graph.add_edge(3, 4, 9) graph.add_edge(3, 5, 14) graph.add_edge(4, 5, 10) graph.add_edge(5, 6, 2) graph.add_edge(6, 7, 1) graph.add_edge(6, 8, 6) graph.add_edge(7, 8, 7)
g.add_edge(('A', 'B')) g.add_edge(('B', 'C')) g.add_edge(('C', 'D')) g.add_edge(('D', 'E')) g.add_edge(('E', 'F')) g.add_edge(('F', 'G')) g.add_edge(('G', 'H')) g.add_edge(('H', 'I')) g.add_edge(('I', 'J')) g.add_edge(('J', 'A')) g.add_edge(('C', 'H')) depth_first_search_traversal(graph=g.graph_dict, starting_vertex='A', goal_vertex='F', verbose=True) path = breadth_first_search_find_path(graph=g.graph_dict, starting_vertex='A', goal_vertex='F', verbose=True) print(path) wg = WeightedGraph() wg.add_edge(('A', 'B'), 7) wg.add_edge(('B', 'C'), 10) wg.add_edge(('A', 'C'), 9) wg.add_edge(('B', 'D'), 15) wg.add_edge(('C', 'D'), 11) wg.add_edge(('A', 'E'), 14) wg.add_edge(('C', 'E'), 2) wg.add_edge(('E', 'F'), 9) wg.add_edge(('F', 'D'), 6) cost, path = djikstra(wg.graph_dict, 'A', 'F', True) print(cost, path)
g.add_edge(('D', 'E')) g.add_edge(('E', 'F')) g.add_edge(('F', 'G')) g.add_edge(('G', 'H')) g.add_edge(('H', 'I')) g.add_edge(('I', 'J')) g.add_edge(('J', 'A')) g.add_edge(('C', 'H')) depth_first_search_traversal(graph=g.graph_dict, starting_vertex='A', goal_vertex='F', verbose=True) path = breadth_first_search_find_path(graph=g.graph_dict, starting_vertex='A', goal_vertex='F') print(path) wg = WeightedGraph() wg.add_edge(('A', 'B'), 1) wg.add_edge(('B', 'C'), 6) wg.add_edge(('C', 'D'), 3) wg.add_edge(('D', 'E'), 8) wg.add_edge(('E', 'F'), 2) wg.add_edge(('F', 'G'), 5) wg.add_edge(('G', 'H'), 1) wg.add_edge(('H', 'I'), 8) wg.add_edge(('I', 'J'), 4) wg.add_edge(('J', 'A'), 3) wg.add_edge(('C', 'H'), 2) cost, path = djikstra(wg.graph_dict, 'A', 'F', True) print(cost, path)
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Pathfinding Algorithm Visualizer") self.layout = QVBoxLayout() columns = 40 rows = 30 self.graph = WeightedGraph(columns, rows) self.grid_ui = GridUI(self.graph, columns, rows) self.grid_ui.setContentsMargins(0, 0, 0, 0) self.grid_ui.setStyleSheet('background-color: white;') self.buttons_layout = QHBoxLayout() self.start_button = QPushButton('Start') self.reset_button = QPushButton('Reset grid') self.path_button = QPushButton('Clear path') self.change_button = QPushButton('Change parameters') self.buttons_layout.addWidget(self.start_button) self.buttons_layout.addWidget(self.reset_button) self.buttons_layout.addWidget(self.path_button) self.buttons_layout.addWidget(self.change_button) self.layout.addWidget(self.grid_ui) self.layout.addLayout(self.buttons_layout) self.widget = QWidget() self.widget.setLayout(self.layout) self.setCentralWidget(self.widget) self.reset_button.clicked.connect(self.clear_grid) self.change_button.clicked.connect(self.show_parameter_popup) self.start_button.clicked.connect(self.generate_path) self.path_button.clicked.connect(self.clear_path) self.parameters = ParametersPopup() self.parameters.buttonBox.accepted.connect( self.update_graph_with_parameters) self.ui_thread = QThread() self.ui_thread.start() self.ui_QObj = UIQObj() self.ui_QObj.moveToThread(self.ui_thread) self.ui_QObj.update.connect(self.handle_ui_update) self.ui_QObj.start.connect(self.ui_QObj.run) self.ui_QObj.start.emit() self.path_thread = QThread() self.path_thread.start() self.path_QObj = PathQObj() self.path_QObj.moveToThread(self.path_thread) self.path_QObj.start.connect(self.path_QObj.run) def closeEvent(self, event) -> None: sys.exit() def clear_grid(self) -> None: self.graph.clear_terrain_nodes() self.clear_path() def clear_path(self) -> None: self.graph.clear_path_nodes() self.graph.clear_frontier_nodes() def show_parameter_popup(self) -> None: self.parameters.raise_() self.parameters.show() def update_graph_with_parameters(self) -> None: start_row = self.parameters.start_row start_col = self.parameters.start_col end_row = self.parameters.end_row end_col = self.parameters.end_col self.graph.startpoint_node = Node(start_col, start_row) self.graph.endpoint_node = Node(end_col, end_row) self.graph.desert_weight = self.parameters.desert_weight self.graph.forest_weight = self.parameters.forest_weight self.graph.visualize_algorithm = self.parameters.visualize_checkBox.isChecked( ) def generate_path(self) -> None: start = self.graph.startpoint_node end = self.graph.endpoint_node option = "b" if self.parameters.a_star_radio.isChecked(): option = "a" elif self.parameters.dijkstra_radio.isChecked(): option = "d" self.path_QObj.start.emit(self.graph, option, start, end) @pyqtSlot() def handle_ui_update(self): self.grid_ui.update()
hm = HeapMap(data=min_heap_dic) while not hm.is_empty_heap(): hm.build_min_heapify() node, _ = hm.pop_min_element() if node in edge_dic: result.append(edge_dic[node]) for vertex in graph[node]: if vertex in min_heap_dic and graph[node][vertex] < min_heap_dic[vertex]: min_heap_dic[vertex] = graph[node][vertex] edge_dic[vertex] = "{0}{1}".format(node, vertex) return result if __name__ == "__main__": graph = WeightedGraph(directed=False) # graph = {'A': {'A': INF, 'B': 3, 'C': INF, 'D': 1, 'E': INF, 'F': INF}, # 'B': {'A': 3, 'B': INF, 'C': 1, 'D': 3, 'E': INF, 'F': INF}, # 'C': {'A': INF, 'B': 1, 'C': INF, 'D': 1, 'E': 5, 'F': 4}, # 'D': {'A': 1, 'B': 3, 'C': 1, 'D': INF, 'E': 6, 'F': INF}, # 'E': {'A': INF, 'B': INF, 'C': 5, 'D': 6, 'E': INF, 'F': INF}, # 'F': {'A': INF, 'B': INF, 'C': 4, 'D': INF, 'E': 2, 'F': INF} # } graph.add_edge('A', 'B', 3) graph.add_edge('A', 'D', 1) graph.add_edge('B', 'C', 1) graph.add_edge('B', 'D', 3) graph.add_edge('C', 'D', 1) graph.add_edge('C', 'E', 5) graph.add_edge('C', 'F', 4) graph.add_edge('D', 'E', 6)
def main(): global matrix with open(sys.argv[1]) as f: lines = f.readlines() matrix = [[int(n) for n in l.strip().split(',')] for l in lines] """ matrix = [[131, 673, 234, 103, 18], [201, 96, 342, 965, 150], [630, 803, 746, 422, 111], [537, 699, 497, 121, 956], [805, 732, 524, 37, 331]] """ matrix_size = len(matrix) # the cost of arriving at each node is the value at that node g = WeightedGraph() for lnum, line in enumerate(matrix): for cnum, value in enumerate(line): g.add_node((lnum, cnum)) # from below if (0 <= lnum + 1 < matrix_size): g.add_arc((lnum + 1, cnum), (lnum, cnum), value) # from above if (0 <= lnum - 1 < matrix_size): g.add_arc((lnum - 1, cnum), (lnum, cnum), value) # from right if (0 <= cnum + 1 < matrix_size): g.add_arc((lnum, cnum + 1), (lnum, cnum), value) # from left if (0 <= cnum - 1 < matrix_size): g.add_arc((lnum, cnum - 1), (lnum, cnum), value) route, cost = a_star(g, (0, 0), (matrix_size - 1, matrix_size - 1)) print(cost + matrix[0][0])