def create_graph(self, start_position, initial_pheromone): # calculate the cooverages of each sensor at each power level for sensor in self.__repository.sensors.values(): sensor.calculate_coverage(self.__repository.mapp) self.__graph = UndirectedGraph() # transform the starting point and each sensor's different states into vertices start_vertex = Vertex(start_position, 0, 0) self.__graph.add_vertex(start_vertex) for sensor in self.__repository.sensors.values(): for i, coverage in enumerate(sensor.coverages): vertex = Vertex(sensor.position, i, coverage) self.__graph.add_vertex(vertex) vertices = list(self.__graph.parse_vertices()) for i in range(len(vertices) - 1): start = vertices[i] for j in range(i + 1, len(vertices)): end = vertices[j] if start.position[0] != end.position[0] and start.position[1] != end.position[1]: path = self.search_a_star( start.position[0], start.position[1], end.position[0], end.position[1]) cost = len(path) edge = Edge(start, end, cost, path, initial_pheromone) self.__graph.add_edge(edge)
def readUndirectedGraph(filename): ''' the information about a graph is read from a given textfile and the graph is created :param filename: the given file :return: the read graph raises ValueError if file not found ''' try: with open(filename, "r") as file: lines = file.readlines() lines[0] = lines[0].strip("\n") graphVerticesAndEdges = lines[0].split(" ") numberOfVertices = int(graphVerticesAndEdges[0]) numberOfEdges = int(graphVerticesAndEdges[1]) graph = UndirectedGraph(numberOfVertices, numberOfEdges) lines = lines[1:] for line in lines: line = line.strip("\n") edge = line.split(" ") vertex1 = int(edge[0]) vertex2 = int(edge[1]) cost = int(edge[2]) graph.addEdge(vertex1, vertex2, cost) except: raise ValueError("File not found") return graph
def test_bfs_undirected(self): graph = UndirectedGraph(6) graph.add_edge(0, 2) graph.add_edge(0, 1) graph.add_edge(0, 5) graph.add_edge(2, 1) graph.add_edge(2, 3) graph.add_edge(2, 4) graph.add_edge(4, 3) graph.add_edge(5, 3) self.assertEqual(graph.bfs(0), [None, 0, 0, 2, 2, 0])
def setUp(self): graph = UndirectedGraph(7) graph.addEdge(0, 1) graph.addEdge(1, 2) graph.addEdge(1, 3) graph.addEdge(1, 4) graph.addEdge(4, 5) graph.addEdge(4, 6) graph.addEdge(0, 4) self.solver = DFSSolver(graph)
def test_dfs_undirected(self): graph = UndirectedGraph(7) graph.add_edge(0, 6) graph.add_edge(0, 2) graph.add_edge(0, 1) graph.add_edge(0, 5) graph.add_edge(6, 4) graph.add_edge(4, 5) graph.add_edge(4, 3) graph.add_edge(5, 3) self.assertEqual(graph.dfs(0), [None, 0, 0, 5, 6, 4, 0])
def setUp(self): self.graph = UndirectedGraph() for i in range(6): self.graph.add_vertex(i+1) self.graph.add_edge(1, 2) self.graph.add_edge(1, 4) self.graph.add_edge(2, 4) self.graph.add_edge(2, 3) self.graph.add_edge(4, 3) self.graph.add_edge(3, 6) self.graph.add_edge(4, 5) self.graph.add_edge(5, 6)
def __ui_read_graph_from_file(self): file_name = input("insert name of the file:\n>>>") with open(file_name, "r") as f: line = f.readline() line = line.strip() parts = line.split() no_of_vertices = int(parts[0]) no_of_edges = int(parts[1]) graph = UndirectedGraph(no_of_vertices) for _ in range(no_of_edges): line = f.readline() line = line.strip() parts = line.split() graph.add_edge(int(parts[0]), int(parts[1]), int(parts[2])) self.__graph = graph
def test_numbers_of_self_loop(self): graph = UndirectedGraph(4) graph.add_edge(2, 2) graph.add_edge(3, 3) self.assertEqual(graph.numbers_of_self_loop(), 2) graph = DirectedGraph(4) graph.add_edge(2, 2) graph.add_edge(3, 3) self.assertEqual(graph.numbers_of_self_loop(), 2)
def save_to_file(graph: UndirectedGraph, file_name: str): with open(file_name, 'w') as data_file: output = f"{graph.vertices_count} {graph.edges_count}\n" for edge in graph.parse_edges(): output += f"{edge.start} {edge.end} {edge.cost}\n" data_file.write(output)
def run(): graph = UndirectedGraph() #random_graph(graph, 100, 10) load_from_file(graph, "graph5.txt") service = Service(graph) ui = UI(graph, service) ui.run() save_to_file(graph, "graph_out.txt")
def readGraph(file): graph_file = open(file, 'r') graph = None for line_no, line in enumerate(graph_file): if line_no == 0: matrix_size = int(line) graph = UndirectedGraph(matrix_size) else: line = line.strip() for col_no, col in enumerate(line): if col == "1": graph.addEdge(line_no - 1, col_no) line_no += 1 graph_file.close() return graph
class TestBFS(unittest.TestCase): def setUp(self): self.graph = UndirectedGraph() for i in range(6): self.graph.add_vertex(i+1) self.graph.add_edge(1, 2) self.graph.add_edge(1, 4) self.graph.add_edge(2, 4) self.graph.add_edge(2, 3) self.graph.add_edge(4, 3) self.graph.add_edge(3, 6) self.graph.add_edge(4, 5) self.graph.add_edge(5, 6) def test_search(self): self.assertTrue(bfs(self.graph, 1, 6)) self.assertFalse(bfs(self.graph, 1, 10))
def _construct_undirected_graph(filename: str) -> UndirectedGraph: """ Private helper function to construct a undirected graph from the given undirected graph file. :param filename: str :return: UndirectedGraph """ with open(filename, 'rt') as f: graph = UndirectedGraph() # Add the vertices n_vtx = int(f.readline()) for vtx_id in range(1, n_vtx + 1): graph.add_vtx(new_vtx_id=vtx_id) # Add the edges for line in f.readlines(): ends = line.split(' ') graph.add_edge(end1_id=int(ends[0]), end2_id=int(ends[1])) return graph
class TestUndirectedGraph(unittest.TestCase): def setUp(self): self.graph = UndirectedGraph(5) def test_vertexCount(self): vertices = self.graph.vertexCount() self.assertTrue(vertices == 5) def test_addEdge(self): self.graph.addEdge(1, 4) self.graph.addEdge(0, 4) self.assertTrue(self.graph.areConnected(0, 4)) self.assertTrue(self.graph.areConnected(4, 0)) self.assertTrue(self.graph.areConnected(1, 4)) self.assertTrue(self.graph.areConnected(4, 1)) self.assertFalse(self.graph.areConnected(0, 1)) def test_adjacentEdges(self): self.graph.addEdge(0, 1) self.graph.addEdge(0, 3) self.graph.addEdge(1, 4) adj_0 = self.graph.adjacentEdges(0) adj_1 = self.graph.adjacentEdges(1) self.assertEqual({Edge(0, 3), Edge(0, 1)}, adj_0) self.assertEqual({Edge(0, 1), Edge(1, 4)}, adj_1) def test_edgeCandidates(self): self.graph.addEdge(0, 1) self.graph.addEdge(1, 2) self.graph.addEdge(1, 3) self.graph.addEdge(1, 4) self.graph.addEdge(2, 3) self.graph.addEdge(0, 4) tree = SpanningTree(5) tree.addEdge(Edge(0, 1)) actual = self.graph.edgeCandidates(tree) expected = {Edge(1, 2), Edge(1, 3), Edge(1, 4), Edge(0, 4)} self.assertEqual(expected, actual) def test_str(self): self.graph.addEdge(0, 1) self.graph.addEdge(0, 3) self.graph.addEdge(1, 4) str = self.graph.__str__() expected = """ | 0 1 2 3 4\n-|-----------\n0| 0 1 0 1 0\n1| 1 0 0 0 1\n2| 0 0 0 0 0\n3| 1 0 0 0 0\n4| 0 1 0 0 0\n""" self.assertEqual(expected, str) if __name__ == '__main__': unittest.main()
def setUp(self): self.client = Redis() self.client.flushdb() self.graph = UndirectedGraph(self.client, "test-graph")
class TestUndirectedGraph(unittest.TestCase): def setUp(self): self.client = Redis() self.client.flushdb() self.graph = UndirectedGraph(self.client, "test-graph") def test_add_edge(self): self.assertEqual(self.graph.get_all_connected_vertexs("a"), set()) self.assertEqual(self.graph.get_all_connected_vertexs("b"), set()) self.graph.add_edge("a", "b") self.assertNotEqual(self.graph.get_all_connected_vertexs("a"), set()) self.assertNotEqual(self.graph.get_all_connected_vertexs("b"), set()) def test_remove_edge(self): self.graph.add_edge("a", "b") self.graph.remove_edge("a", "b") self.assertEqual(self.graph.get_all_connected_vertexs("a"), set()) self.assertEqual(self.graph.get_all_connected_vertexs("b"), set()) def test_has_edge(self): self.assertFalse(self.graph.has_edge("a", "b")) self.assertFalse(self.graph.has_edge("b", "a")) self.graph.add_edge("a", "b") self.assertTrue(self.graph.has_edge("a", "b")) self.assertTrue(self.graph.has_edge("b", "a")) def test_get_all_connected_vertexs(self): self.assertEqual(self.graph.get_all_connected_vertexs("a"), set()) self.assertEqual(self.graph.get_all_connected_vertexs("b"), set()) self.graph.add_edge("a", "b") self.assertEqual(self.graph.get_all_connected_vertexs("a"), {"b"}) self.assertEqual(self.graph.get_all_connected_vertexs("b"), {"a"})
def setUp(self): self.graph = UndirectedGraph(5)
def test_findBestSolutionFor10(self): graph = UndirectedGraph(10) graph.addEdge(0, 4) graph.addEdge(0, 5) graph.addEdge(0, 6) graph.addEdge(0, 8) graph.addEdge(0, 9) graph.addEdge(1, 2) graph.addEdge(1, 3) graph.addEdge(1, 5) graph.addEdge(1, 6) graph.addEdge(1, 7) graph.addEdge(1, 8) graph.addEdge(2, 6) graph.addEdge(2, 7) graph.addEdge(2, 9) graph.addEdge(3, 5) graph.addEdge(3, 6) graph.addEdge(3, 7) graph.addEdge(4, 5) graph.addEdge(4, 6) graph.addEdge(4, 8) graph.addEdge(4, 9) graph.addEdge(5, 9) graph.addEdge(6, 7) graph.addEdge(6, 9) graph.addEdge(7, 8) solver = DFSSolver(graph) # self.solver.DEBUG = True solution, price = solver.findBestSolution() self.assertEqual(2, price) expected = [Edge(0, 9), Edge(1, 2), Edge(1, 3), Edge(3, 5), Edge(4, 5), Edge(4, 8), Edge(6, 7), Edge(6, 9), Edge(7, 8)] self.assertEqual(set(expected), set(solution.edgeList()))
player = CanvasImagePlayer(C, playerImgSrc, (cellSize, cellSize), cellOffset) ### Grid rects = [] for x in xrange(cells): rects.append([]) for y in xrange(cells): newX = cellOffset + (x * cellSize) newY = cellOffset + (y * cellSize) newX2 = newX + cellSize newY2 = newY + cellSize newRect = C.create_rectangle(newX, newY, newX2, newY2) rects[x].append(newRect) ### Graph ug = UndirectedGraph() possibleBlocks = random.sample(xrange(1, cells * cells), blockCount) blocked = [(i % cells, i / cells) for i in possibleBlocks] # create graph paths for x in xrange(cells): for y in xrange(cells): if not (x, y) in blocked: if x + 1 < cells and not (x + 1, y) in blocked: ug.addPath((x, y), (x + 1, y), 1) if x - 1 >= 0 and not (x - 1, y) in blocked: ug.addPath((x, y), (x - 1, y), 1) if y + 1 < cells and not (x, y + 1) in blocked: ug.addPath((x, y), (x, y + 1), 1) if y - 1 >= 0 and not (x, y - 1) in blocked: ug.addPath((x, y), (x, y - 1), 1) # change the fill of the blocked grid locations
class TestUndirectedGraph(unittest.TestCase): def setUp(self): self.graph = UndirectedGraph(5) def test_vertexCount(self): vertices = self.graph.vertexCount() self.assertTrue(vertices == 5) def test_addEdge(self): self.graph.addEdge(1, 4) self.graph.addEdge(0, 4) self.assertTrue(self.graph.areConnected(0, 4)) self.assertTrue(self.graph.areConnected(4, 0)) self.assertTrue(self.graph.areConnected(1, 4)) self.assertTrue(self.graph.areConnected(4, 1)) self.assertFalse(self.graph.areConnected(0, 1)) def test_adjacentEdges(self): self.graph.addEdge(0, 1) self.graph.addEdge(0, 3) self.graph.addEdge(1, 4) adj_0 = self.graph.adjacentEdges(0) adj_1 = self.graph.adjacentEdges(1) self.assertEqual([Edge(0, 1), Edge(0, 3)], adj_0) self.assertEqual([Edge(0, 1), Edge(1, 4)], adj_1) def test_edgeCandidates(self): self.graph.addEdge(0, 1) self.graph.addEdge(1, 2) self.graph.addEdge(1, 3) self.graph.addEdge(1, 4) self.graph.addEdge(2, 3) self.graph.addEdge(0, 4) tree = SpanningTree(5) tree.addEdge(Edge(0, 1)) actual = self.graph.edgeCandidates(tree) expected = [Edge(1, 2), Edge(1, 3), Edge(1, 4), Edge(0, 4)] self.assertEqual(set(expected), set(actual)) def test_str(self): self.graph.addEdge(0, 1) self.graph.addEdge(0, 3) self.graph.addEdge(1, 4) str = self.graph.__str__() expected = """ | 0 1 2 3 4\n-|-----------\n0| 0 1 0 1 0\n1| 1 0 0 0 1\n2| 0 0 0 0 0\n3| 1 0 0 0 0\n4| 0 1 0 0 0\n""" self.assertEqual(expected, str) if __name__ == '__main__': unittest.main()
def test_edge_added_undirected(self): graph = UndirectedGraph(7) graph.add_edge(2, 9) self.assertEqual(graph.edge, 0) self.assertEqual(graph.adj_list[2], []) self.assertNotEqual(len(graph.adj_list), 9) graph.add_edge(0, 1) graph.add_edge(0, 5) graph.add_edge(6, 0) graph.add_edge(6, 4) graph.add_edge(2, 3) self.assertEqual(graph.edge, 5) self.assertEqual(graph.adj_list[3], [2]) self.assertEqual(graph.adj_list[2], [3]) graph.add_edge(3, 2) self.assertEqual(graph.edge, 5) graph.add_edge(2, 0) graph.add_edge(3, 5) graph.add_edge(4, 2) graph.add_edge(4, 3) graph.add_edge(5, 4) self.assertEqual(graph.edge, 10)
from undirected_graph import UndirectedGraph, Node, Edge nodes = [ Node(0), Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8) ] edges = [ \ Edge(nodes[0], nodes[3], 2), \ Edge(nodes[0], nodes[4], 4), \ Edge(nodes[4], nodes[1], 3), \ Edge(nodes[1], nodes[2], 1), \ Edge(nodes[1], nodes[5], 7), \ Edge(nodes[2], nodes[5], 6), \ Edge(nodes[5], nodes[8], 4), \ Edge(nodes[5], nodes[7], 0), \ Edge(nodes[8], nodes[7], 8), \ Edge(nodes[7], nodes[6], 9)] graph = UndirectedGraph(nodes, edges)
class Controller: def __init__(self, repository): self.__repository = repository self.__graph = None def search_a_star(self, initial_x, initial_y, final_x, final_y): openn = [] closed = [] parents = {} start = (initial_x, initial_y) goal = (final_x, final_y) start_distances = {} goal_distances = {} openn.append(start) parents[start] = None start_distances[start] = 0 while openn: current = min(openn, key=lambda o: start_distances.get( o, 0) + goal_distances.get(o, 0)) if current == goal: path = [] path.append(current) while parents[current]: current = parents[current] path.append(current) return path[::-1] openn.remove(current) closed.append(current) neigbhors = utils.get_neighbors( self.__repository.mapp, current[0], current[1]) for node in neigbhors: if node in closed: continue new_distance = start_distances[current] + 1 if node in openn: if start_distances[node] > new_distance: start_distances[node] = new_distance parents[node] = current else: start_distances[node] = new_distance goal_distances[node] = utils.manhattan( node[0], node[1], goal[0], goal[1]) parents[node] = current openn.append(node) return [] def create_graph(self, start_position, initial_pheromone): # calculate the cooverages of each sensor at each power level for sensor in self.__repository.sensors.values(): sensor.calculate_coverage(self.__repository.mapp) self.__graph = UndirectedGraph() # transform the starting point and each sensor's different states into vertices start_vertex = Vertex(start_position, 0, 0) self.__graph.add_vertex(start_vertex) for sensor in self.__repository.sensors.values(): for i, coverage in enumerate(sensor.coverages): vertex = Vertex(sensor.position, i, coverage) self.__graph.add_vertex(vertex) vertices = list(self.__graph.parse_vertices()) for i in range(len(vertices) - 1): start = vertices[i] for j in range(i + 1, len(vertices)): end = vertices[j] if start.position[0] != end.position[0] and start.position[1] != end.position[1]: path = self.search_a_star( start.position[0], start.position[1], end.position[0], end.position[1]) cost = len(path) edge = Edge(start, end, cost, path, initial_pheromone) self.__graph.add_edge(edge) def epoch(self, ant_energy, ants_count, q0, cost_power, pheromone_power, evaporation_rate): ants = [] vertices = list(self.__graph.parse_vertices()) # create ants for i in range(ants_count): vertex = vertices[0] ant = Ant(vertex, ant_energy) ants.append(ant) running = True while running: running = False for ant in ants: if ant.finished: continue ant.move(self.__graph, q0, cost_power, pheromone_power) running = True costs = [ant.cost(self.__graph) for ant in ants] min_cost = min(costs) f = [1 / (cost - min_cost + 1) for cost in costs] for edge in self.__graph.parse_edges(): edge.pheromone *= 1 - evaporation_rate for i, ant in enumerate(ants): for j in range(len(ant.path) - 1): v1 = ant.path[j] v2 = ant.path[j + 1] edge = self.__graph.get_edge(v1, v2) edge.pheromone += f[i] best_i = max(range(len(ants)), key=lambda i: f[i]) best_ant = ants[i] return (best_ant.path, f[i]) def solve(self, ant_energy, ants_count, q0, cost_power, pheromone_power, evaporation_rate, epoch_count): sol = ([], -1) best_sol = ([], -1) for i in range(epoch_count): sol = self.epoch(ant_energy, ants_count, q0, cost_power, pheromone_power, evaporation_rate) if sol[1] > best_sol[1]: best_sol = sol return best_sol def update_sensors(self, vertices): for sensor in self.__repository.sensors.values(): sensor.power = 0 for vertex in vertices: if vertex.position in self.__repository.sensors: sensor = self.__repository.sensors[vertex.position] sensor.power = vertex.power def get_path(self, vertices): path = [] for i in range(len(vertices) - 1): v1 = vertices[i] v2 = vertices[i + 1] edge = self.__graph.get_edge(v1, v2) edge_path = edge.path if edge.path[0] != v1.position: edge_path = edge_path[::-1] path += edge_path return path @ property def map(self): return self.__repository.mapp @ property def sensors(self): return self.__repository.sensors def save_map(self, file_name='test.map'): self.__repository.save_map(file_name) def load_map(self, file_name='test.map'): self.__repository.load_map(file_name)
def test_max_degree_undirected(self): graph = UndirectedGraph(7) graph.add_edge(0, 1) graph.add_edge(0, 3) graph.add_edge(0, 5) self.assertEqual(graph.max_degree(), 3)
return False def contains_cycle(self): for i in range(self.vertices_count): if not self.visited[i]: if self.dfs(i, -1): return True return False if __name__ == '__main__': # https://www.geeksforgeeks.org/detect-cycle-undirected-graph/ graph = UndirectedGraph() graph.add_edge(1, 0) graph.add_edge(1, 2) graph.add_edge(2, 0) graph.add_edge(0, 3) graph.add_edge(3, 4) dfs_graph = DetectCycleDFS(graph) if dfs_graph.contains_cycle(): print('contains cycle!') else: print('no cycle found') graph2 = UndirectedGraph() graph2.add_edge(0, 1) graph2.add_edge(1, 2) dfs_graph2 = DetectCycleDFS(graph2)
neighborVertex.cost = newCost neighborVertex.prev = current # current is end # is the final node unreachable if vertexes[current].cost == float("Inf"): return None # walk back from current, using vertex.prev, building the list finalPath = [] while vertexes[current].cost != 0: finalPath.append(vertexes[current].index) current = vertexes[current].prev finalPath.append(current) # return the list and the final cost return (list(reversed(finalPath)), vertexes[finalPath[0]].cost) ug = UndirectedGraph(10) startEndOptions = range(ug.nodeCount) start = startEndOptions.pop(random.randint(0, len(startEndOptions) - 1)) end = startEndOptions.pop(random.randint(0, len(startEndOptions) - 1)) print 'paths', ug.paths print 'costs', ug.costs print 'path from', start, 'to', end print dijkstra(ug, start, end)
self.dfs(i) def dfs(self, at): self.visited[at] = True # marking connecting components of 'at' self.connected_components[at] = self.count neighbors = self.graph.get_adjacent_vertices(at) for neighbor in neighbors: if not self.visited[neighbor]: self.previous[neighbor] = at self.dfs(neighbor) if __name__ == '__main__': # create graph and add edges for testing bfs graph = UndirectedGraph() #graph = DirectedGraph() # graph in Algorithms pg. 529 graph.add_edge(0, 5) graph.add_edge(4, 3) graph.add_edge(0, 1) graph.add_edge(9, 12) graph.add_edge(6, 4) graph.add_edge(5, 4) graph.add_edge(0, 2) graph.add_edge(11, 12) graph.add_edge(9, 10) graph.add_edge(0, 6) graph.add_edge(7, 8) graph.add_edge(9, 11) graph.add_edge(5, 3)